2

I am fairly new to C and I don't understand why the following two statements do not create the same result:

char *fields[14] = {NULL};

const int num_fields = 14;
char *fields[num_fields] = {NULL};

Option 1 works, but option 2 does not. It says "variable-sized object may not be initialized" and it gives a warning "warning: excess elements in array initializer". I use gcc 4.2.1 on OSX.

Thanks for sharing your thoughts!

1
  • I think this is probably because a const int isn't necessarily a constant value, crazy as that may seem. I believe you can obtain a pointer to the const and modify the underlying value. Commented Jan 31, 2012 at 14:29

4 Answers 4

5

The second object is called a VLA (Variable Length Array), well defined by C99. To achieve what you want you can use this:

for (i = 0; i < num_fields; i++)
    fields[i] = NULL;

The gist of the issue is that const int num_fields is very different from 14, it's not a constant, it's read-only.

Sign up to request clarification or add additional context in comments.

4 Comments

+1 but technically it's not initialization, but assignment. I guess it would be correct to say that VLAs cannot be initialized per se.
@ArmenTsirunyan I changed the wording.
Thank you cnicutar for your explanation!
In a VLA (Variable Length Array) the compiler automatically handles the storage management. Since the size won´t be known until runtime, you can´t use the initializer. As everybody said. You need a for loop.
3

Even if you define num_fields with const keyword, compiler interprets it as variable only. you can have alternative for this by defining following macro:

#define num_fields 14

char *fields[num_fields] = {NULL};

Comments

1

Although num_fields has a const qualifier, it is still considered a variable by the compiler.

Therefore, you are attempting to declare a variable-sized array, and initialisers (the {NULL} part) cannot be used in conjunction with them.

1 Comment

Thank you Blagovest Buyukliev for your response.
0

Your construction works in C++, where a const int will be treated as a compile-time constant ("constant expression"), and hence available for use as a compile-time array size.

(This aspect was one of B. Stroustrup's design goals for C++, to eliminate the need for compile-time macros if possible)

However in C, your definition of "num_fields" effectively declares a read-only memory location with your preset value, and hence is not under C rules a "constant expression" valid at compile time, and hence may not be used as an array size at the outermost 'program' scope.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.