我正在学习灵活的数组成员。我根据我正在学习的书中的2行示例编写了下面的代码。该代码与gcc -Wall
一起编译,没有错误,并且执行时没有错误。灵活的char数组成员结构
但是我不知道这个malloc
呼叫的结尾是什么(n
)。我假设如果我将一个字符串存储在灵活数组中,我应该在字符串上调用strlen()
,并使用返回值(n
)。无论我分配什么值(n
),代码似乎都能正常工作,甚至在没有(n
)时也能正常工作。
struct vstring *str = malloc(sizeof(struct vstring) + n);
需要或不需要的值?
#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;
}
使用'fgets'字符串它更好:) – 0decimal0 2014-09-27 13:37:52