NO

Author Topic: Is there a way to declare a struct pointer and assign values in one line?  (Read 3477 times)

Gary Willoughby

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

like this, maybe?

Code: [Select]
struct RECT *a = {10, 20, 30, 40};
this errors, btw.

JohnF

  • Guest
Re: Is there a way to declare a struct pointer and assign values in one line?
« Reply #1 on: December 30, 2009, 10:14:07 PM »
Is there a way to declare a struct pointer and assign values in one line?

like this, maybe?

Code: [Select]
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

Offline DMac

  • Member
  • *
  • Posts: 272
Re: Is there a way to declare a struct pointer and assign values in one line?
« Reply #2 on: December 31, 2009, 06:05:24 PM »
You can do it in two lines, no less.

Code: [Select]
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:

Code: [Select]
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

  • Guest
Re: Is there a way to declare a struct pointer and assign values in one line?
« Reply #3 on: December 31, 2009, 09:13:44 PM »
He did ask about a struct pointer.

John
« Last Edit: December 31, 2009, 09:16:17 PM by JohnF »

Offline Stefan Pendl

  • Global Moderator
  • Member
  • *****
  • Posts: 582
    • Homepage
Re: Is there a way to declare a struct pointer and assign values in one line?
« Reply #4 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:
Code: [Select]
struct RECT a = {10, 20, 30, 40};
myfun(&a);
---
Stefan

Proud member of the UltraDefrag Development Team

Offline frankie

  • Global Moderator
  • Member
  • *****
  • Posts: 2096
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:
Code: [Select]
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:
Code: [Select]
struct RECT *a = &((struct RECT ){10, 20, 30, 40});
« Last Edit: January 05, 2010, 11:03:36 PM by frankie »
It is better to be hated for what you are than to be loved for what you are not. - Andre Gide