我的主要功能中有一個結構。我將該指標傳遞給另一個執行某些操作的函式,如果滿足條件,它將它傳遞給另一個函式以進行填充。當回傳主函式時,該t結構不包含mydata復制到其中的任何資料。
typedef struct _t {
int one;
int two;
int three;
int four;
} T;
void second(T *t) {
t = malloc(20);
memcpy(t, mydata, 20);
}
void first(T *t) {
second(t);
}
int main() {
T t;
first(t);
}
我需要在這里使用雙指標嗎?如果 is 的地址t并且0x1000我將其傳遞給first()then 不會參考t只是 be0x1000嗎?就像我將指標傳遞給second()?
uj5u.com熱心網友回復:
在這個答案中,我假設由于未顯示的原因,您實際上確實需要進行動態記憶體分配。如果不是這種情況,則唯一需要進行的更改是替換first(t);為first(&t);,并洗掉t = malloc(20);。
要解決的第一個問題是tinmain應該有型別T *,而不是T. 您正在進行動態記憶體分配,并且似乎想將該指標存盤在 中t,因此您需要:T *t;.
第二個問題是您想操縱tin的值main,但將其按值傳遞給first。相反,您需要將指標傳遞給tinto first: first(&t);。
T修復這兩個問題后,您現在將指向(型別&t)的指標傳遞給firstand second,因此您需要將它們的簽名分別更改為void first(T **t)and void second(T **t)。
應用這兩項更改,以及進行一些小的樣式調整,我們得到:
typedef struct T {
int one;
int two;
int three;
int four;
} T;
void second(T **t_ptr) {
*t_ptr = malloc(20);
memcpy(*t_ptr, mydata, 20);
}
void first(T **t_ptr) {
second(t_ptr);
}
int main() {
T *t;
first(&t);
}
另一件缺少且需要添加的事情是檢查 的成功malloc,但我沒有將其添加到上面的代碼中。
此外,您在問題中顯示的內容不應該編譯;您將結構傳遞給接受指標的函式。
uj5u.com熱心網友回復:
您的問題對于新的 C 開發人員來說很常見。實際上你有兩個。
第一個問題是你通過值傳遞你的結構。該first函式被宣告為接收一個指向T但您傳遞t而不是傳遞的指標&t(這是t- 的地址,當函式接受指標時,這是您想要的)。
但是還有另一個問題,即使您按照上面的建議更改代碼,它仍然無法正常作業。second使用 分配記憶體malloc。該函式T作為指標接收T *t。您分配mallocto的輸出t實際上覆寫了t指向的內容(如果t之前分配過,您將在此處泄漏記憶體)。
波紋管你可以看到你想要的正確代碼。
typedef struct _t {
int one;
int two;
int three;
int four;
} T;
/* Make sure we have some data to initialize */
T mydata = {0};
/*
We take a pointer to a pointer and change what the external pointer points to. */
In our example when this function is called *ppt is NULL
and t is a pointer to t in main()
*/
void second(T **ppt) {
/*
We never calculate the size of structures by hand. It can change depending on
OS and architecture. Best let the compiler do the work.
*/
*ppt = (T*)malloc(sizeof(T));
memcpy(*ppt, &mydata, sizeof(T));
}
void first(T **ppt) {
/* Make sure we don't leave dangling pointers. */
if (NULL != *ppt)
free(*ppt);
second(ppt);
}
int main() {
T *t = NULL; /* A pointer to our data */
/*
We pass a pointer to our pointer so that the function can change the value it
holds
*/
first(&t);
/* Always do an explicit return if the type of the function is not void */
return 0;
}
如何理解正在發生的事情:
首先,我們宣告t一個指向持有型別的記憶體的指標,T并確保將指標初始化為指向 NULL(這是一個約定,意味著指標未初始化)。
我們有一個函式可以使用malloc. malloc從堆中分配記憶體并回傳該記憶體的地址。(實際上,指標只是一個在記憶體中保存地址的變數)。我們想將該地址放在t宣告的 in 中main()。為此,我們需要將地址傳遞給分配函式,t以便對其進行修改。為此,我們使用address of運算子 - &。這就是我們這樣呼叫函式的原因first(&t)。
Our allocating function accepts a pointer to a pointer. This is because we want to change the address t points to. So we declared the parameter as T **ppt. It holds the address of the pointer *t in main. In the function we dereference the pointer to the pointer to get the original pointer we want to assign the address malloc returns.
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/440919.html
上一篇:類構造中的C 指標
