I have the following code:
int b = 10; // maximum branching
typedef struct depth * depth;
struct depth{
int number ;
depth child[b] ;// <---- Error here
};
And the following error:
variably modified ‘child’ at file scope
I have the following code:
int b = 10; // maximum branching
typedef struct depth * depth;
struct depth{
int number ;
depth child[b] ;// <---- Error here
};
And the following error:
variably modified ‘child’ at file scope
Try this instead:
#define MAX_BRANCHING 10
int b = MAX_BRANCHING; // maximum branching
typedef struct depth * depth;
struct depth{
int number ;
depth child[MAX_BRANCHING] ;//<---- Error here
};
"Variable length arrays" (VLAs) were introduced in C99 and C11, but their use is "conditional" (compilers are not required to implement the feature). In C++, the preferred technique is to use "const int". In C, I would recommend using a #define
. IMHO...
If b
can't be constant, and you don't want to use heap allocation for the child array, you can use this, rather peculiar workaround (hint: consider NOT using this, but using heap allocation for the array):
typedef struct depth *depth_p;
struct depth
{
int number;
depth_p child[0];
};
The trick is, that the following statement is still valid:
depth_p d = get_depth();
d->child[5]; // <-- this is still valid
In order to use this, you need to create instances of depth_p
in this (and only this) way:
depth_p create_depth(int num_children)
{
return (depth_p)malloc(
sizeof(struct depth) + num_children * sizeof(depth_p)
);
}
Firstly, this allocates memory for all the other members (int number
) with sizeof(struct depth)
. Then, it allocates additional memory for the required amount of children by adding num_children * sizeof(depth_p)
.
Don't forget to free your depth
references with free
.