1

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

3 Answers3

1

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...

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

paulsm4
  • 114,292
  • 17
  • 138
  • 190
  • Other than "const", you have two choices: 1) make "depth" the max possible size, or 2) make "depth" a pointer, and intialize it with `malloc(b * sizeof (int))` at runtime. – paulsm4 Nov 09 '13 at 19:18
  • 1
    mmmmm ,b must be entered by user , i cant make it constant !! –  Nov 09 '13 at 19:18
  • 1
    okay , thank you , i will make it max possible size , but i think that affect on space, i mean that it will take more space , since i want to code "Depth First algorithm" –  Nov 09 '13 at 19:23
1

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.

dialer
  • 4,348
  • 6
  • 33
  • 56
0

Sructs can't have dynamic members so try const int b = 10;

rgs
  • 61
  • 1
  • 5