开发者

Why do we use static with array of pointers?

开发者 https://www.devze.com 2022-12-27 18:15 出处:网络
Why do we use static with array of pointers? What is the relation between static and array of pointers?

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

For example:

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

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

int main()
{
   static int a[]={1,2,3};
   static int *p[]={a,a+1,a+2}; 
   ...
   return 0;
开发者_StackOverflow}


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号