malloc for struct and pointer in C

前端 未结 8 1876
忘了有多久
忘了有多久 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:50

    Few points

    struct Vector y = (struct Vector*)malloc(sizeof(struct Vector)); is wrong

    it should be struct Vector *y = (struct Vector*)malloc(sizeof(struct Vector)); since y holds pointer to struct Vector.

    1st malloc() only allocates memory enough to hold Vector structure (which is pointer to double + int)

    2nd malloc() actually allocate memory to hold 10 double.

    0 讨论(0)
  • When you allocate memory for struct Vector you just allocate memory for pointer x, i.e. for space, where its value, which contains address, will be placed. So such way you do not allocate memory for the block, on which y.x will reference.

    0 讨论(0)
提交回复
热议问题