假设我有一个结构:
typedef struct {
int number1; /* dummy */
int number2; /* dummy */
int number3; /* dummy */
char *name1;
char name2[];
} Klass;
其余的代码是:
int main(int argc, char const *argv[])
{
char *name1 = "this is a name"; /* 1st case */
char name2[] = "this is also a name"; /* 2nd case */
Klass k;
k.number1 = 10;
k.number2 = 20;
k.number3 = 30;
k.name1 = "this is my first name"; /* 3rd case */
/* error: invalid use of flexible array member */
k.name2 = "this is my second name";
Klass *kp = (Klass*)malloc(sizeof(Klass));
kp->number1 = 100;
kp->number2 = 200;
kp->number3 = 300;
kp->name1 = "this is also my first name"; /* 4th case */
/* error: invalid use of flexible array member */
kp->name2 = "this is my second name";
return 0;
}
- 谁能为我澄清在标记的情况下如何分配内存(堆与堆栈)?
我应该如何在主块的末尾释放内存?编译器给出的原因是error: invalid use of flexible array member
什么?
编辑
如果你说k.name = "this is my name";
并且kp->name = "this is also my name";
在堆栈上,你能解释一下我是如何达到"this is my name"
这样的:
Klass *kp;
int foo() {
Klass k;
k.number1 = 10;
k.number2 = 20;
k.number3 = 30;
k.name = "this is my name";
kp = &k;
} // k is destroyed now
int main(int argc, char const *argv[])
{
kp = (Klass*)malloc(sizeof(Klass));
foo();
printf("%d\n", kp->number1); /* segfault */
printf("%d\n", kp->number2); /* segfault */
printf("%d\n", kp->number3); /* segfault */
printf("%s\n", kp->name); /* prints "this is my name" */
return 0;
}