DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C (http://www.daniweb.com/forums/forum118.html)
-   -   Malloc a struct (http://www.daniweb.com/forums/thread158790.html)

dusse Nov 21st, 2008 10:25 am
Malloc a struct
 
Hello guys..
I´m trying to do something like the code below ..
struct node{
      int a;
      char *s;
};       

void main()
{
    node *x;
    int sMAX = 3;
    int nodeMAX = 10;
     
    x = (node*)malloc((sizeof(int)+sizeof(char)*sMAX)*nodeMAX);
...
}
in other words I want to alloc dynamically the number of nodes and also the length of s in node struct
I tried a lot of things like:
x = (node*)malloc((sizeof(node)*nodeMAX);
x = (node*)malloc((sizeof(struct node)*nodeMAX);
x = (node*)malloc((sizeof(node)+sizeof(char)*sMAX)*nodeMAX);
and my code do not run
Is it possible to do what I want?
thanks.

Narue Nov 21st, 2008 11:27 am
Re: Malloc a struct
 
>I want to alloc dynamically the number of nodes and also the length of s in node struct
Do it separately:
struct node *x = malloc ( nodeMAX * sizeof *x );
int i;

for ( i = 0; i < nodeMAX; i++ )
  x->s = malloc ( sMAX );
>Is it possible to do what I want?
In C89, not without invoking undefined behavior. In C99 the "struct hack" has been blessed and is directly supported as a flexible array member:
struct node{
  int a;
  char s[];
};

struct node *x = malloc ( nodeMAX * ( sizeof *x + sMAX ) );

devnar Nov 21st, 2008 12:38 pm
Re: Malloc a struct
 
Also, in C, shouldn't
node *x;
be
struct node *x;
?

Another note - main returns int.

Narue Nov 21st, 2008 1:33 pm
Re: Malloc a struct
 
>Also, in C, shouldn't node *x; be struct node *x; ?
Indeed. I've been working in mixed C/C++ too much these days. :icon_rolleyes:


All times are GMT -4. The time now is 5:36 am.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC