0

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.

3
Contributors
3
Replies
6
Views
8 Years
Discussion Span
Last Post by Narue
0

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

>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:

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.