[英]Error in initialization of a pointer to structure
我有這個程序,我正在嘗試修改它,但我不明白為什么聲明:struct Link * temp = cap; 不打印我分配給鏈表的號碼。 提前致謝!
struct Link
{
int data;
struct Link *urmatorul;
};
void Insert(Link * cap, int n)
{
struct Link * temp = (Link*)malloc(sizeof(struct Link));
temp->data = n;
temp->urmatorul = NULL;
if(cap != NULL)
temp->urmatorul = cap;
cap = temp;
}
void Print(Link * cap)
{
struct Link *temp = cap;
printf(" %d", cap->data);
printf("The number is: ");
while(temp != NULL)
{
printf(" %d", temp->data);
temp = temp->urmatorul;
}
printf("\n");
}
int main()
{
struct Link * cap;
cap = NULL;
printf("How many numbers? \n");
int x, n, i;
scanf(" %d", &x);
for(i = 0; i < x; ++i)
{
printf("Enter the number: \n");
scanf("%d", &n);
Insert(cap, n);
Print(cap);
}
return 0;
}
您需要通過引用傳遞Link *
來更改它,這是一個Link **
void Insert(Link **cap, int n)
{
struct Link * temp = (Link*)malloc(sizeof(struct Link));
temp->data = n;
temp->urmatorul = NULL;
if(*cap != NULL)
temp->urmatorul = *cap;
*cap = temp;
}
並在你的main(...)
使用
Insert(&cap, n);
或者你可以像這樣從你的Insert(...)
返回新的Link *
;
Link * Insert(Link * cap, int n)
{
struct Link * temp = (Link*)malloc(sizeof(struct Link));
temp->data = n;
temp->urmatorul = NULL;
if(cap != NULL)
temp->urmatorul = cap;
return temp;
}
並在你的main(...)
使用
cap = Insert(cap, n);
這條線沒有做任何事情,因為cap
內Insert
是副本cap
從main
:
cap = temp;
Insert
退出后,更改將被丟棄,因此main
的cap
仍為NULL
。
更改Insert
的簽名以返回Link*
,並將其分配給來自main
的調用中的cap
:
Link* Insert(Link * cap, int n)
{
struct Link * temp = malloc(sizeof(struct Link)); // No need to cast
temp->data = n;
temp->urmatorul = cap; // No need for the conditional
return temp;
}
電話看起來像這樣:
cap = Insert(cap, n);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.