tags:

views:

115

answers:

2

Why do we use static with array of pointers? What is the relation between static and array of pointers?

For example:

main()
{
  int a[]={1,2,3};
  int *p[]={a,a+1,a+2}; 
  ......
}

This code shows illegal initialization - why? Whereas the following code works:

main()
{
   static int a[]={1,2,3};
   static int *p[]={a,a+1,a+2}; 
   ......
}

Please do clear my doubt as soon as possible....

+8  A: 

In C89 (the original "ANSI C"), values used in initialiser lists must be "constant expressions". One type of constant expression is an address constant, and a pointer to an object with static storage duration is an address constant.

However, a pointer to an object with automatic storage duration is not an address constant (its value is not known at compile-time), so it cannot be used in an initialiser list.

You only need to make the array a have static storage duration - the following will work too:

main()
{
  static int a[]={1,2,3};
  int *p[]={a,a+1,a+2}; 
  ......
}

C99 has relaxed this restriction for initialisers for objects that have automatic storage duration (which is why gcc is OK with it).


Why is it so? Initialiser lists are typically used for initialising potentially large objects, like arrays or structures. Objects with automatic storage duration must be initialised anew each time the function is entered, and the C89 rules allow compiler writes to do this initialisation by emitting a simple memcpy() call (using as source a static "template", which corresponds to the initialiser list). Under the C99 rules, the compiler potentially has to emit an arbitrarily complicated block of initialisation code.

caf
A: 

With Visual C, the code works. However, it generates a level 4 warning C4204, meaning they consider this is a Microsoft-specific extension to the C-standard. As caf and AndreyT said, it is not part of the C standard to allow this.

EDIT: With C standard I mean C89.

Daniel Rose
Well, it's part of the C standard that's been current for more than a decade now. Unfortunately that standard is still not supported by Visual C.
caf
True, Microsoft is still in the process of fully supporting C99...
Daniel Rose