[英]Error in initialization of a pointer to structure
I have this program that I'm trying to modify it, but I don't understand why the statement: struct Link * temp = cap; 我有这个程序,我正在尝试修改它,但我不明白为什么声明:struct Link * temp = cap; doesn't print me the number that I assigned to the linked list.
不打印我分配给链表的号码。 Thanks in advance!
提前致谢!
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;
}
You need to pass the Link *
by reference to change it, that's a Link **
您需要通过引用传递
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;
}
and in your main(...)
use 并在你的
main(...)
使用
Insert(&cap, n);
or you could return the new Link *
from your Insert(...)
like this; 或者你可以像这样从你的
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;
}
and in your main(...)
use 并在你的
main(...)
使用
cap = Insert(cap, n);
This line does not do anything, because cap
inside Insert
is a copy of cap
from the main
: 这条线没有做任何事情,因为
cap
内Insert
是副本cap
从main
:
cap = temp;
The change gets discarded as soon as Insert
exits, so main
's cap
remains NULL
. Insert
退出后,更改将被丢弃,因此main
的cap
仍为NULL
。
Change Insert
's signature to return Link*
, and assign it to cap
in the call from main
: 更改
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;
}
The call looks like this: 电话看起来像这样:
cap = Insert(cap, n);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.