0

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.

9
  • 1
    "something is wrong with my mallocs" - well, the code you posted here doesn't free any of the allocated memory, so that might be the problem Commented Jul 27, 2020 at 18:01
  • What’s “something”? Please show the valgrind output. Commented Jul 27, 2020 at 18:02
  • Thanks, I'm gonna post it Commented Jul 27, 2020 at 18:03
  • 10,100,010 (80,000 direct, 10,020,010 indirect) bytes in 1 blocks are definitely lost in loss record 6 of 6 Error is detected at the line 'n->arr = malloc(sizeof(char*)*length_of_first_array); ' Commented Jul 27, 2020 at 18:09
  • 2
    If you use a VLA of pointers in your struct -- how will the compiler ever be able to determine the size for that struct type at compile time? Makes pointer arithmetic impossible -- you can't have a variable sized object as a member of a struct save and except for a Flexible Array Member as it's last member C11 Standard - 6.7.2.1 Structure and union specifiers(p3). A VLA != FAM Commented Jul 27, 2020 at 19:09

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.