malloc for struct and pointer in C

前端 未结 8 1955
忘了有多久
忘了有多久 2020-12-04 04:57

Suppose I want to define a structure representing length of the vector and its values as:

struct Vector{
    double* x;
    int n;
};

Now,

8条回答
  •  自闭症患者
    2020-12-04 05:42

    In principle you're doing it correct already. For what you want you do need two malloc()s.

    Just some comments:

    struct Vector y = (struct Vector*)malloc(sizeof(struct Vector));
    y->x = (double*)malloc(10*sizeof(double));
    

    should be

    struct Vector *y = malloc(sizeof *y); /* Note the pointer */
    y->x = calloc(10, sizeof *y->x);
    

    In the first line, you allocate memory for a Vector object. malloc() returns a pointer to the allocated memory, so y must be a Vector pointer. In the second line you allocate memory for an array of 10 doubles.

    In C you don't need the explicit casts, and writing sizeof *y instead of sizeof(struct Vector) is better for type safety, and besides, it saves on typing.

    You can rearrange your struct and do a single malloc() like so:

    struct Vector{    
        int n;
        double x[];
    };
    struct Vector *y = malloc(sizeof *y + 10 * sizeof(double));
    

提交回复
热议问题