Search code examples
cstandardsvariable-length-arraypointer-to-array

Pointer to array of runtime-determined size pre-C99


Before C99, does the C standard allow defining or casting to pointers to arrays of length determined at runtime?

I understand that the standard doesn't allow variable length arrays before C99, but whether pointers to arrays of runtime-determined size are allowed is not obvious to me, since the compiler knows how much memory to allocate for a pointer at compile time, unlike the array.

gcc 10.1.0 allows it, even with -std=c90, but I am curious about whether the standard allows it rather than whether specific compilers do. This question is very similar, but the answer doesn't talk about the standard.

Here is a code example:

#include <stdio.h>

int f() {
    int a;
    scanf("%d", &a)
    return a;
}
int main() {
    int dim1 = f();
    int dim2 = 2*dim1;

    int (*p)[dim1][dim2];  // is this allowed pre-C99?
    return 0;
}

Solution

  • This is a constraint violation. A conforming C89 compiler must issue a diagnostic for this program.

    3.5.4.2 Array declarators

    Constraints

    The expression that specifies the size of an array shall be an integral constant expression that has a value greater than zero.

    With gcc use -std=c90 -pedantic to get (mostly) conforming mode.