我想在struct S中声明一个int num.然后同一个struct也应该有一个大小为num的数组B(所以将从它自己的struct B访问num).
在功能中,我能做到,
func(int A)
{
int max=A; //I could use A directly, I am just trying to explain my plan.
int B[max];
}
Run Code Online (Sandbox Code Playgroud)
同样不适用于struct,
struct S {
int num;
int data[num]; //this is wrong, num is undeclared
};
Run Code Online (Sandbox Code Playgroud)
有什么方法可以做到这一点吗?
使用灵活的阵列成员:
struct S {
int num;
int data[];
};
int x = 42;
struct S *p = malloc(sizeof (struct S) + sizeof (int [x]));
p->num = x;
Run Code Online (Sandbox Code Playgroud)