Is there a way to declare a struct pointer and assign values in one line?

Started by Gary Willoughby, December 30, 2009, 07:53:22 PM

Previous topic - Next topic

Gary Willoughby

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.

JohnF

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

DMac

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.
No one cares how much you know,
until they know how much you care.

JohnF

He did ask about a struct pointer.

John

Stefan Pendl

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);

---
Stefan

Proud member of the UltraDefrag Development Team

frankie

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});
"It is better to be hated for what you are than to be loved for what you are not." - Andre Gide