Pelles C forum

C language => Beginner questions => Topic started by: Gary Willoughby on December 30, 2009, 07:53:22 PM

Title: Is there a way to declare a struct pointer and assign values in one line?
Post by: Gary Willoughby on December 30, 2009, 07:53:22 PM
Is there a way to declare a struct pointer and assign values in one line?

like this, maybe?

struct RECT *a = {10, 20, 30, 40};

this errors, btw.
Title: Re: Is there a way to declare a struct pointer and assign values in one line?
Post by: JohnF on December 30, 2009, 10:14:07 PM
Quote from: Gary Willoughby on December 30, 2009, 07:53:22 PM
Is there a way to declare a struct pointer and assign values in one line?

like this, maybe?

struct RECT *a = {10, 20, 30, 40};

this errors, btw.

That will not do because there is no space allocated for the struct, all you have is space allocated for a pointer to a struct.

So the answer to your question I think is no.

John
Title: Re: Is there a way to declare a struct pointer and assign values in one line?
Post by: DMac on December 31, 2009, 06:05:24 PM
You can do it in two lines, no less.

typedef struct tagRECT { long l; long t; long r; long b; } RECT;
RECT rc = {1,2,3,4};


Now if you are using the windows api, RECT is already declared, so in your method doing the following:

VOID MyMethod(void){
     RECT rcTxt = { 0, 0, 10, 5 };


Declares an instance of and initialize your struct.
Title: Re: Is there a way to declare a struct pointer and assign values in one line?
Post by: JohnF on December 31, 2009, 09:13:44 PM
He did ask about a struct pointer.

John
Title: Re: Is there a way to declare a struct pointer and assign values in one line?
Post by: Stefan Pendl on December 31, 2009, 10:01:18 PM
You can only initialize a struct, if you need a pointer to a struct as an argument for a function you usually use &struct, if I am not mistaken.

So one would use the following:
struct RECT a = {10, 20, 30, 40};
myfun(&a);

Title: Re: Is there a way to declare a struct pointer and assign values in one line?
Post by: frankie on January 05, 2010, 10:59:35 PM
You have to specify that you want to assign the address of the defined struct, and you have to specify that the initialization data is the struct you need with a cast.
Look the following example:
typedef struct {int a; int b; int c;} tst;
tst *r = &((tst){1, 2, 3});
tst *s = &((tst){4, 5, 6});
.... etc.

In your case:
struct RECT *a = &((struct RECT ){10, 20, 30, 40});