C语言中结构体和指针的malloc - malloc for struct and pointer in C

问题:

Suppose I want to define a structure representing length of the vector and its values as:假设我想定义一个表示向量长度及其值的结构:

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

Now, suppose I want to define a vector y and allocate memory for it.现在,假设我想定义一个向量 y 并为其分配内存。

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

My search over the internet show that I should allocate the memory for x separately.我在互联网上的搜索表明我应该单独为 x 分配内存。

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

But, it seems that I am allocating the memory for y->x twice, one while allocating memory for y and the other while allocating memory for y->x, and it seems a waste of memory.但是,似乎我为 y->x 分配了两次内存,一次为 y 分配内存,另一次为 y->x 分配内存,这似乎是浪费内存。 It is very much appreciated if let me know what compiler really do and what would be the right way to initialize both y, and y->x.如果让我知道编译器真正做了什么以及初始化 y 和 y->x 的正确方法是什么,我将不胜感激。

Thanks in advance.提前致谢。


解决方案:

参考: https://stackoom.com/en/question/zxtG
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章