問題:
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.提前致謝。