ohhConti
ohhConti

Reputation: 71

Handle variable string arrays inside a struct (C)

I have to know if there is a way to declare inside a struct a variable length string array, something like that

struct node {
               int k;
               char * arr[length_variable];
            }

Now I'm doing something like that

 struct node {
                  int k;
                  char ** arr;
                 }

int main()
{
  ...
  struct node * n = (struct node*)malloc(sizeof(struct node));
  n->arr = malloc(sizeof(char*)*length_of_first_array); //the length of the array is variable
  n->arr[0] = malloc(sizeof(char)*length_first_string+1); //+1 is for \0 character
  strcpy(n->arr[0],"word");
  ...
}

Unfortunately analising the output code using valgrind tool 'memory check' it seems that something is wrong with my mallocs.

Upvotes: 0

Views: 70

Answers (1)

John Bode
John Bode

Reputation: 123588

A VLA may not be a member of a struct or union type:

6.7.2.1 Structure and union specifiers
...
9 A member of a structure or union may have any complete object type other than a variably modified type.123)...
123) A structure or union cannot contain a member with a variably modified type because member names are not ordinary identifiers as defined in 6.2.3.
C 2011 Online Draft

The code you've posted is correct as far as allocation is concerned - are you properly deallocating that memory when you're done with it? You have to make sure you free each n->arr[i] before you free n->arr, and you have to free n->arr before freeing n.

Upvotes: 2

Related Questions