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.

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

Also, in C, shouldn't node *x; be struct node *x; ?

Another note - main returns int.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.