views:

603

answers:

1

Hey,

I am learning C and I am playing around with pointers and arrays. I am trying to create an array of pointers with the code below:

const int NUM_P = 50; // Line 10
char *pS[NUM_P] = { NULL }; // Line 11

I am getting the following warnings and errors when I compile:

→ gcc array.c -o array
array.c: In function ‘main’:
array.c:11: error: variable-sized object may not be initialized
array.c:11: warning: excess elements in array initializer
array.c:11: warning: (near initialization for ‘pS’)

I cannot figure this error out, I have looked online and been unable to find a explanation and solution of the problem.

Can anyone help out?

Cheers

Eef

+5  A: 

Your main problem is the initialization line (= {NULL};) because apparently you can't initialize an array that way when the array's size is a variable. If you use #define NUM_P 50 to force the array size to be a true compile-time constant, then the array would not have a variable size, and your initialization method would compile fine.

As a side note, the difference between #define NUM_P 50 and const int NUM_P = 50 is that C89 does not allow the use of variables as array dimensions, but C99 does; however, C99 is not fully supported by all compilers yet. The fact that gcc accepts your character array with a size of NUM_P is not C89-compliant.

Technically, you could use a flag on the command line to tell gcc that you want to compile in C99:

gcc -std=c99 FILE.c

By the way, when learning C, start at the top of the errors listed and work down from there. In this case, the warnings are not of any concern until you've taken care of the error at the top: "variable-sized object may not be initialized".

Mark Rushakoff
Thanks, taking the '= {NULL};' out fixed the issue and it runs ok. I am actually following the book 'C - Novice to Professional' and it had that as part of source for a tutorial! It now works, thanks again. Eef
Eef