Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

c - Variable-length array in file scope?

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
", 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...