struct中的一个元素可以在C中访问其自身的另一个元素吗?

Reg*_*ser 4 c struct pointers

我想在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)

有什么方法可以做到这一点吗?

oua*_*uah 6

使用灵活的阵列成员:

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)

  • @Olaf我正在重用OP使用的成员名称,如果`int`对于OP值足够宽,则不需要`num`为`size_t`. (2认同)