I’m studying flexible array members. I've written the code below based on a 2 line example in the book I'm studying from. The code compiles with gcc -Wall with no errors and also executes without error.
However I don’t know what the (n) at the end of this malloc call is for. I assume if I'm storing a string the the flexible array, I'm supposed to call strlen() on the string and use the returned value for (n). The code seems to work no matter what value I assign to (n) and even works when there is no (n).
struct vstring *str = malloc(sizeof(struct vstring) + n);
Is the value needed or not?
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct vstring{
int len;
char chars[]; /* c99 flexible array member to store a variable string */
};
int main()
{
char input_str[20];
int n = 0; /* what should n be it doesn’t seem to matter what value I put in here */
struct vstring * array[4]; /* array of pointers to structures */
int i = 0;
while ( i < 4 )
{
printf("enter string :");
scanf("%s",input_str);
struct vstring *str = malloc(sizeof(struct vstring) + n );
strcpy(str->chars,input_str);
str->len = strlen(input_str);
array[i] = str;
i++;
}
for ( i = 0 ; i < 4 ; i++) {
printf("array[%d]->chars = %s len = %d\n", n, array[i]->chars, array[i]->len);
}
return 0;
}
fgetsfor strings its better :)