我對串列和指標有疑問,讓我解釋一下。讓我們定義一個這樣的串列:
typedef struct list *LIST;
typedef struct node *link;
struct list{link head; int n;};
struct node{Item val;link next;};
n 節點的數量在哪里,LIST 是指向結構串列的指標(我必須這樣做,因為我想創建一個指向串列的不透明指標,在我的作業中,LIST 指標會進入.h并且structs會進入.c但那是不是問題,我知道我應該避免這樣宣告指標)。
Item 型別也是通過一個不透明的指標宣告的,所以我有這樣的東西:
typedef struct info *Item;
struct info{char *name;int N};
我的問題是我不明白如何在這個串列中插入東西。(所以我想在串列中添加一個 Item 型別,但我不能因為 Item 是一個指標所以,例如,如果嘗試這樣做:
//the lists is already initialized and let's say we want to add 3 nodes
Item x=malloc(sizeof(*x));`
x->name=calloc(10,sizeof(char));
for(int i=0;i<3;i ){
fscanf("%s",x->name);
fscanf("%d",x->N);//this is a random number
ListInsert(L,x);
}
這就是我在 ListInsert() 中的內容:
void ListInsert(LIST L, Item x){
link z,p;
if(L->head==NULL)
L->head=newNode(x,L->head);
else{
for(z=L->head->next, p=L->head;z!=NULL;p=x, z=z->next);//i know a tail would help
p->next=newNode(x,z);
}
}
這就是我在 newNode() 中所擁有的:
link newNode(item x,link next){
link z=malloc(sizeof(*z));//should control the allocation was successful I know
z->val=x;
z->next=next;
return z;
}
每當我修改 value 時x,我實際上是在修改 head 和所有內容指向的內容,這是我的問題,有什么解決方案?也許做一個陣列?指標有時很難理解,例如我應該分配z->val->name嗎?
uj5u.com熱心網友回復:
當你說 ...
每當我修改 value 時
x,我實際上是在修改 head 和所有內容指向的內容,這是我的問題,有什么解決方案?
...我認為您正在談論此代碼:
Item x=malloc(sizeof(*x));` x->name=calloc(10,sizeof(char)); for(int i=0;i<3;i ){ fscanf("%s",x->name); fscanf("%d",x->N);//this is a random number ListInsert(L,x); }
實際上,您只分配了一個struct info并指定x指向它。您已將其添加struct info到您的鏈接串列中 3 次,并且還對其進行了多次修改。
假設您的目標是將三個不同的物件添加到串列中,則解決方案首先分配三個不同的物件(否則它們來自哪里?)。由于每個都有一個指向動態分配陣列的指標,因此您還需要為每個陣列分配一個單獨的陣列。實作這一目標的最簡單方法是將分配移動到回圈中:
for (int i = 0; i < 3; i ) {
Item x = malloc(sizeof(*x));
x->name = calloc(10, sizeof(char));
fscanf("%s", x->name);
fscanf("%d", x->N); //this is a random number
ListInsert(L, x);
}
如果您被允許修改所涉及的結構,那么您還可以考慮使陣列的name元素struct info具有合適的長度而不是指標。這有點不太靈活,但這意味著每個專案只需要一個分配,而不是兩個。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/406173.html
標籤:
