【发布时间】:2018-02-06 21:08:52
【问题描述】:
我有这个程序,我正在尝试修改它,但我不明白为什么会有这样的声明: 结构链接 * 温度 = 上限; 不会打印我分配给链接列表的数字。 提前致谢!
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;
}
【问题讨论】:
-
C 按值传递参数。您的
cap是NULL,在Insert()之后从未更改。 -
回想一下你的课本或课堂笔记。他们对将参数传递给函数有什么看法?你还记得任何关于它的按价值吗?这意味着它们是复制的,无论您在函数内部对副本进行多少修改,原始的都不会改变?做一些关于在C中模拟通过引用传递的研究。
-
Insert 需要返回你的链表的新根节点。您的插入函数正在泄漏内存。
标签: c struct linked-list