[英]get the value from pointer to pointer in struct
我有一個結構:
struct structname
{
structname** link;
int total;
}
我想將structname1
鏈接到structname2
。 我所做的是:
int *ptr = &structname2;
structname1 -> link = &ptr;
然后我嘗試訪問structname1
的鏈接,即structname2
:
structname *test = structname1 -> link;
這是正確的方法嗎? 當我嘗試打印時,打印了一些未知符號。 有人可以幫我弄這個嗎? 謝謝。
您必須按照以下方式進行。
struct structname structname1, structname2; //define two structures structname1 and structname2 of type structname.
struct structname * ptr; // ptr is a pointer to struct of type structname.
struct structname ** ptr2 // ptr2 is a double pointer to struct of type structname.
ptr = &structname2; // ptr points to structname2
ptr2 = &ptr; // ptr2 points to ptr and ptr points to structname2;
structname1.link = ptr2; // now link is a double pointer to structname2.
如果我錯了或遺漏了,請讓我糾正
您的代碼中有幾處錯誤。 首先,你把ptr
的類型弄錯了:它應該是struct structname **
而不是int *
。
但是如果你正在嘗試做一個鏈表,你根本不需要雙重間接級別。 這很可能是您想要的:
struct structname
{
struct structname *link;
int total;
}
這樣,將structname1
與structname2
鏈接起來structname1
簡單了(假設structname1
和structname2
是struct structname
類型):
struct structname *ptr = &structname2;
structname1.link = ptr;
如果structname1
和structname2
的類型為struct structname *
,那么您需要改為:
struct structname *ptr = structname2;
structname1->link = ptr;
您也可以刪除中間變量ptr
,這里用處不大。
struct node {
struct node *next;
int cargo;
}
struct node *current, *last, *next;
unsigned char i;
current = (struct node*)(calloc(sizeof(struct node)));
for (last = current, unsigned char i = 5; i--;) {
next = (struct node*)(calloc(sizeof(struct node)));
next->cargo = i;
last->next = next;
}
上面的代碼是一個非常簡單的鏈表。 請注意,與您的代碼相比,我更改了一些內容。 我使用calloc
創建對象,這意味着對象將在堆上而不是堆棧上分配。 這也不需要您為每個元素(也就是鏈表中的節點)提供明確的名稱。 這也意味着當你離開名稱的范圍時它不會被破壞。 當然,當您不再需要該列表時,您將需要稍后釋放所有節點。
那么你不需要一個指向節點中的指針的指針,一個簡單的指針就足夠了。 在您的主程序中,您還應該使用適當的指針。 盡管所有指針的大小都相同並且可以相互轉換,但您應該 - 只要有可能 - 使用正確的類型。
在這里,我在循環中創建了另外 5 個節點,以演示“這種方法的靈活性”。
如果你想做一個循環鏈表,那也很容易。 只需附加這些行:
next->next = current;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.