LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 632|回复: 3

指针的问题!!请教高手

[复制链接]
发表于 2004-9-4 19:59:58 | 显示全部楼层 |阅读模式
我的代码如下,编译没问题,但运行时却出错。我怀疑是指针的错误,请高手指教。^_^

#include <stdio.h>
#include <malloc.h>
struct node
{
        int                        data;
        struct node *next;
};
void createlist(struct node *head)
{
        int e;
        struct node *p;

        head=(struct node *)malloc(sizeof(struct node));
        head->next=NULL;

        printf("输入非零数据(遇零结束)\n");
        scanf("%d",&e);
        while(e!=0)
        {
                p=(struct node *)malloc(sizeof(struct node));
                p->data=e;
                p->next=head->next;
                head->next=p;
                scanf("%d",&e);
        }
}
void display(struct node *head)
{
        while(head->next)
        {
                printf("%d\t ",head->next->data);
                head=head->next;
        }
        printf("\n");
}

int main()
{
        struct node head;
        createlist(&head);
        display(&head);
        return 0;
}
发表于 2004-9-4 20:56:41 | 显示全部楼层
createlist(struct node *head)定义错了,应该用 createlist(struct node **head) 或者 createlist((struct node*)& head)(如果用C++,推荐用这个)。因为这个地方需要改变的是指针的值,而不是指针指向的内容,所以需要指向指针的指针,或者用指针的引用。推荐使用引用是因为这样可以避免用NULL调用这个函数(createlist(NULL)这种情况一定会出错的)
 楼主| 发表于 2004-9-4 21:16:09 | 显示全部楼层

指针的指针怎么用啊?

楼上高手,请你说的再清楚一些好吗?我还没用过指针的指针。不好意思,我比较菜!!
发表于 2004-9-6 10:08:08 | 显示全部楼层
很简单,如果你需要在函数中修改变量的值,那么要把变量的指针传进去;现在是需要在函数中修改指针的值,那么对应的,就是要把指针的指针传进去了。
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表