我有这个程序,我正在尝试修改它,但我不明白为什么声明: 结构链接 * 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);
关于c - 结构指针初始化错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48651991/