DrDee
DrDee

Reputation: 3609

How to initialize a dynamic array of pointers to NULL in C?

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!

Upvotes: 2

Views: 12495

Answers (4)

MikeW
MikeW

Reputation: 6130

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.

Upvotes: 0

codestriker
codestriker

Reputation: 61

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};

Upvotes: 3

cnicutar
cnicutar

Reputation: 182754

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.

Upvotes: 5

Blagovest Buyukliev
Blagovest Buyukliev

Reputation: 43558

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.

Upvotes: 1

Related Questions