0

I declare a variable 'ptr' like this:

int array[4][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
int n = 4;

int (*ptr)[n] = (int (*)[n])array[0];

When put it in global,I got a error when compile the program:

error: variably modified ‘ptr’ at file scope
 int (*ptr)[n] = (int (*)[n])array[0];
       ^

but it will be successful,when I put it in local.

btw:I use the gcc compiler.

zwh
  • 172
  • 2
  • 12

1 Answers1

3

Variables with variably modified type are only permitted at block scope (i.e. inside a function).

Variably modified type means an array type where one of the dimensions is not known at compile-time, or any type derived from that (e.g. pointer to such an array, as in your example).

int (*ptr)[n] has variably modified type because n is not a constant expression. For historical reasons, const int n = 4; would not count as a constant expression either. But #define n 4 would be a constant expression.

One workaround is to write:

int (*ptr)[ sizeof array / sizeof array[0] ] = &array[0];   // note: no cast required

Background: Variably modified type was added in C99, to support arrays whose dimension are not known until runtime.

Although actually using such an array is risky due to stack overflow, this syntax enables some nice follow-on effects. For example, the ability to use array syntax with malloc'd arrays, and the ability to have a function which can operate on a multi-dimensional array using array syntax; but accept various sizes of array.

For rationale as to why they are not permitted at file scope, see the answers to this question. (Currently that question is incorrectly closed as duplicate, but the answers are good)

Community
  • 1
  • 1
M.M
  • 138,810
  • 21
  • 208
  • 365
  • Value of n can be computed as below also right? #define n (sizeof(array)/sizeof(array[0])) int (*ptr)[n] = &array[0] – Gopi Sep 30 '14 at 04:14
  • Yes, `#define` is just a text replacement. – M.M Sep 30 '14 at 04:19
  • In fact,I just use it in a function,like this void fun(int array[], int n).But I really don't understand how it work?Why can I declare a variables with variably modified type?:) – zwh Sep 30 '14 at 04:24
  • 1
    In a function parameter list there are no arrays; `int array[]` [is actually a pointer](http://stackoverflow.com/questions/22677415/why-do-c-and-c-compilers-allow-array-lengths-in-function-signatures-when-they/22677793#22677793) in sheep's clothing. – M.M Sep 30 '14 at 04:30
  • Yeah.But I really wanna know why I can not use it in global? – zwh Sep 30 '14 at 04:44