Variable-length array in file scope?

前端 未结 2 478
别那么骄傲
别那么骄傲 2020-12-20 05:45

I have this code for example.

#include 
#include 
#define array_size 3

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

v         


        
2条回答
  •  粉色の甜心
    2020-12-20 06:12

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

提交回复
热议问题