C 代码错误:"variably modified ‘child’ at file scope"



我有以下代码:

int b = 10; // maximum branching
typedef struct depth * depth;
struct depth{
    int number ;
    depth child[b] ;// <---- Error here
};

以及以下错误:

在文件范围内可变修改的"子项"

试试这个:

#define MAX_BRANCHING 10
int b = MAX_BRANCHING; // maximum branching 
typedef struct depth * depth;
struct depth{
   int number ;
   depth child[MAX_BRANCHING] ;//<---- Error here 
};
"

可变长度数组"(VLA)在C99和C11中引入,但它们的使用是"有条件的"(编译器不需要实现该功能)。 在C++中,首选的技术是使用"const int"。 在 C 中,我建议使用 #define . 恕我直言...

http://en.wikipedia.org/wiki/Variable-length_array

如果b不能是常量,并且您不想对子数组使用堆分配,则可以使用这个相当特殊的解决方法(提示:考虑不要使用它,而是对数组使用堆分配):

typedef struct depth *depth_p;
struct depth
{
    int number;
    depth_p child[0];
};

诀窍是,以下语句仍然有效:

depth_p d = get_depth();
d->child[5]; // <-- this is still valid

为了使用它,您需要以这种(并且仅以这种方式)创建depth_p实例:

depth_p create_depth(int num_children)
{
    return (depth_p)malloc(
        sizeof(struct depth) + num_children * sizeof(depth_p)
    );
}

首先,这用sizeof(struct depth)所有其他成员(int number)分配内存。然后,它通过添加 num_children * sizeof(depth_p) 为所需数量的子级分配额外的内存。

不要忘记使用 free 释放您的depth引用。

Sructs 不能有动态成员,所以尝试 const int b = 10;

相关内容

最新更新