链表的问题
我对这个小程序有疑问。它为列表增加了一些价值。如果我取消注释 //printf("%d",first->val);
程序会出错。一切似乎都很好;(
#include <stdio.h>
#include <stdlib.h>
typedef struct element {
struct element *next;
int val;
} el_listy;
el_listy *first = 0;
void add_to_list(el_listy *lista, int value)
{
if(lista == 0)
{
lista = malloc (sizeof(el_listy));
lista->val = value;
lista->next = 0;
printf("added as first \n");
}
else
{ printf("added as fsecond \n");
el_listy *wsk = lista,*tmp;
while(wsk->next != 0) wsk = wsk->next;
tmp = malloc (sizeof(el_listy));
tmp->val = value;
tmp->next = 0;
wsk->next = tmp;
}
}
int main ()
{
add_to_list(first,2);
add_to_list(first,4);
//printf("%d",*first->val);
system("pause");
return 0;
}
I have a problem with this small program. It added some value to list. If I uncomment //printf("%d",first->val);
the program gives error. Everything seems to be ok ;(
#include <stdio.h>
#include <stdlib.h>
typedef struct element {
struct element *next;
int val;
} el_listy;
el_listy *first = 0;
void add_to_list(el_listy *lista, int value)
{
if(lista == 0)
{
lista = malloc (sizeof(el_listy));
lista->val = value;
lista->next = 0;
printf("added as first \n");
}
else
{ printf("added as fsecond \n");
el_listy *wsk = lista,*tmp;
while(wsk->next != 0) wsk = wsk->next;
tmp = malloc (sizeof(el_listy));
tmp->val = value;
tmp->next = 0;
wsk->next = tmp;
}
}
int main ()
{
add_to_list(first,2);
add_to_list(first,4);
//printf("%d",*first->val);
system("pause");
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是的,这是一个简单的错误。
fitsr 在调用 *add_to_list()* 函数后不会改变。
你应该像这样定义函数:
Yes, it's a simple mistake.
fitsr won't change after *add_to_list()* function is called.
You should define function like this:
first->val
就像(*first).val
一样,您不能同时使用它们。另外,正如missingno所说,add_to_list
永远不会改变first
你应该传递它的地址作为参数,而不是指针本身,这意味着add_to_list(&first,4);
(并更改add_to_list
的实现)first->val
is just like(*first).val
, you can't use them both. also, as missingno said,add_to_list
never changesfirst
you should pass it's address as argument, not the pointer itself, meaningadd_to_list(&first,4);
(and change the implementation ofadd_to_list
as well)你的程序永远不会改变
first
的值。它仍然是一个空指针,因此在取消引用时会出现错误。Your program never changes the value of
first
. It remains a null pointer and thus gives an error when dereferenced.->
已经跟随一个指针,因此*
尝试将first
视为指向el_listy
的指针。您可能会发现cdecl
有帮助。->
already follows a pointer, so the*
tries to treatfirst
as pointer to pointer toel_listy
. You might findcdecl
helpful.您应该使用
(*first).val
或first->val
。否则你会得到错误的间接级别。You should use either
(*first).val
orfirst->val
. Otherwise you get the wrong level of indirection.