考慮以下代碼:
#include<stdio.h>
struct word {
char* data;
};
struct sentence {
struct word* data;
int word_count;
};
struct paragraph {
struct sentence* data ;
int sentence_count;
};
struct document {
struct paragraph* data;
int paragraph_count;
};
void main()
{
int total_paragraph = 5; //I'm myself assigning total number of paragraphs for simplicity
struct document doc;
doc.data = malloc(total_paragraph*(sizeof(struct paragraph))); //Statement which I have a doubt!!!
....
....
....
}
首先,從邏輯上講,該陳述句(malloc 陳述句,我對此有疑問)是否有效?
如果是,計算機如何在不知道大小的情況下分配 5 個記憶體單元(每個單元是 struct 段落大小)struct paragraph(因為我們還沒有對其內容data進行分配,指向結構句型別的指標)?
uj5u.com熱心網友回復:
在沒有定義子結構的情況下分配結構是不可能的。畢竟,如果不知道其子結構的大小,就無法知道結構的大小。
但是,struct paragraph不包含任何子結構。它包含一個結構指標、一個int和可能的填充。所有這些東西的大小都是已知的。
您發布的代碼非常好。
uj5u.com熱心網友回復:
不知道結構段落的大小(因為我們還沒有對其內容進行分配,指標資料指向結構句子型別)?c指標結構
為什么我們需要malloc一個結構來知道它的大小?這個結構的大小是多少?
struct document {
struct paragraph* data;
int paragraph_count;
};
它有一個指標和一個整數。指標具有固定大小(通常在 64 位機器上為 64 位,在 32 位機器上為 32 位)并且整數具有固定大小(通常為 32 位)。因此,以位元組為單位結構的大小是sizeof(any_pointer) sizeof(int) 填充。所有這三個都是編譯器已知的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/389134.html
上一篇:C的指標問題
