Return structure with flexible array member

后端 未结 7 1844
栀梦
栀梦 2021-01-15 03:23

I need to return a structure with a flexible array member from a C function but can\'t figure out why it doesn\'t compile. I know that returning arrays can be achieved by en

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-15 04:06

    Few things:

    1) change the struct defenation to:

     struct data_array {
        long length;
        double* data;
              ^
    };
    

    2) This is how you should use malloc to allocate memory for your array:

    a.data =  malloc (length * sizeof(double));
    

    EDIT

    There are too many mistakes, just follow this code:

    #include 
    #include 
    struct data_array {
        long length;
        double* data;
    };
    struct data_array* test (int length) {
        struct data_array* a;
        a = malloc (sizeof (data_array));
        a->data = malloc (length*sizeof(double));
        a->length = length;
        return a;
    }
    
    int main () {
        data_array* x;
        x = test (5);
        for (int i=0; i<5; i++) {
            x->data[i] = i+0.5;
        }
        for (int i=0; i<5; i++) {
            printf ("%f\n" , x->data[i]);
        }
    }
    

    NOTE that you might need to add casting to the types when useing maloc (my visual force me to do so, otherwise it's compile error. But it simply worng).

提交回复
热议问题