2016-04-10 20 views
-2

如果我已經創建了一個數據結構名稱節點,那麼這意味着我已經創建了一個數據結構,其中包含一個int變量和一個指向另一個節點的地址的指針。但那麼我們爲什麼要聲明temp,temp1start作爲節點*start,*temp,*temp1而不是節點*starttemp,temp1使用創建節點作爲C中鏈接列表中結構類型的指針?

由於temptemp1在程序作爲暫時的「節點」,並宣佈他們爲指針,以結構節點不應該使其工作後使用,但這個節點*temp*temp1作品。爲什麼?

總之爲什麼這些temptemp1聲明爲指針來構造而不是節點temptemp1和爲什麼他們工作(即節點*temp*temp1)?

+1

這取決於它們如何使用。如果你真的需要複製節點,那麼你是對的,你需要節點而不是指針。但更可能的是,您只需要臨時指向節點的指針,在這種情況下,聲明就是他們應該是的。但是沒有看到代碼,我們只能猜測。 –

+0

您錯過*幫助中心*中*如何詢問*部分所需的*相關可縮減可驗證*代碼段,因此很難爲您的問題提供背景信息。 – Wtower

回答

0

基於假設/猜測,因爲你的問題沒有可用的代碼。

舉個例子,如果你正在創建鏈接列表與此類似,

struct node { 
    int value; 
    struct node *link; 
}; 

如果您正在使用struct node temp, temp2然後創建兩個結構變量temptemp2與內存大小等於所有成員的內存大小結構是int + struct node *

如果您正在使用struct node *temp, *temp2然後它會創建兩個指針,可以指向struct node變量。指針只需指向內存位置就會消耗更少的內存。

所以,如果你正在做的一樣,

struct node start; 
start.value = 10; 
start.link = 2000; //hypothetically for example, address should be in hex 
struct node temp = start; 
temp.value = 20; // Will change only value to 20 for temp variable only 

那麼start所有成員的值將裏面temp成員被複制。單獨的內存爲starttemp變量。

如果你正在做的一樣,

struct node start; 
start.value = 10; 
start.link = 2000; 
struct node *temp = &start; 
temp->value = 20; //Will change value to 20 for both temp and start. As temp is pointer not a separate variable. 

然後temp是指針變量指向start位置。