I am reading the book Let us C by Yashavant Kanetkar.
In the Array of Pointers section there is a section of code which is giving me problems:
int main()
{
static int a[] = {0, 1, 2, 3, 4}; //-----------(MY PROBLEM)
int *p[] = {a, a+1, a+2, a+3, a+4};
printf("%u %u %d\n", p, *p, *(*p));
return 0;
}
What I don't understand is: Why has the array a
have to be initialized as static? I tried initializing it without the static keyword, but I got an error saying "illegal".
C90 (6.5.7) had
All the expressions in an initializer for an object that has static storage duration or in an initializer list for an object that has aggregate or union type shall be constant expressions.
And you are initializing an object that has an aggregate type, so the value must be known at compile time and the address of automatic variables are not in that case.
Note this has changed in C99 (6.7.8/4)
All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.
The constraint on object with aggregate or union type has been removed and I've not found it placed somewhere else. Your code with static removed should be accepted by a C99 compiler (it is by gcc -std=c99
for instance, which seems to confirm that I've not overlooked a constraint elsewhere).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With