Variable-length array in file scope?

2019-01-27 05:34发布

问题:

I have this code for example.

#include <stdlib.h>
#include <stdio.h>
#define array_size 3

typedef struct {
    int array[array_size];
} TEST;

void printout(TEST *p, int element) {
    printf("element: %i\n", p->array[element]);
}

int main(void) {
    TEST *p;
    p = malloc(sizeof(TEST));
    p->array[0] = 5;
    printout(p, 0);

    return 0;
} 

But I'd like to assign "array_size" based on user input.

If I try to do so, the compiler says "variably modified ‘array_size’ at file scope". So, am I right that the only way to do what I want is to move everything to main()..?

It works just fine, but keeping structs and functions declarations in file scope seems, you know, neat.

回答1:

The simplest approach is to just allocate the memory dynamically:

typedef struct {
    int *array;
    size_t size;
} TEST;

int main() {
    size_t elem_count = /* from user input */
    TEST p;
    p->array = malloc(elem_count * sizeof int);
    if(!p->array)
        return -1;

    p->size = elem_count;
    /* ... */
    free(p->array);
}


回答2:

You can indeed not define a variable length array at file scope, you can however define a pointer at file scope and malloc it, just define a global pointer int* p = NULL; (lose the whole TEST stuff) and p = malloc(sizeof(int) * input_size); simply access with p[x].

For completeness, you can also use the so called flexible array member defined in C99:

From ISO/IEC 9899:1999, Section 6.7.2.1, paragraph 16:

As a special case, the last element of a structure with more than one named member may have an incomplete array type; this is called a flexible array member.

typedef struct {
    other_type other_data
    int array[];
} TEST;

...

TEST *p = malloc(sizeof(TEST) + sizeof(int) * input_size);

Though note that this is limited to a single member, you could make an array of structs if you would otherwise have multiple arrays of different types but the same length.

This was originally intended mostly for data with headers such as ofter encountered in file and/or network I/O.



标签: c scope