-2
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
struct node{
int value;
struct node *link;
}*p,**q,*r,*temp;
static int n=0;
void append(struct node **,int);
main(){
append(&p,1);
append(&p,2);
append(&p,3);
append(&p,4);
append(&p,5);
printf("Entered linked list :\n");
//display(p);
getch();
}
void append(struct node **q,int num){
if(n==0){
    struct node *temp=(struct node*)malloc(sizeof(struct node));
    temp->value=num;
    temp->link=NULL;
    *q=p;
    n++;
}
else{
    temp=*q;
    while(temp->link!=NULL)
        temp=temp->link;
    r=(struct node*)malloc(sizeof(struct node));
    r->value=num;
    r->link=NULL;
    temp->link=r;
    //q=p;
}
}

有人可以告诉我为什么这个消息:

linkedlist.c.exe 中 0x00fa14ea 处的未处理异常:0xC000005:访问冲突读取位置 0x0000004

在 Visual Studio 2010 中运行此程序时即将到来?

4

2 回答 2

1

if(n==0){
    struct node *temp=(struct node*)malloc(sizeof(struct node));
    temp->value=num;
    temp->link=NULL;
    *q=p;
    n++;
}

您设置*q为全局指针p(即NULL),您的意思是

*q = temp;

当然。

于 2012-08-27T22:05:45.377 回答
1

看起来您正在通过 NULL 指针访问数据。您可以通过错误来判断:

Access violation reading location 0x0000004

当您收到错误提示您已读取 NULL 附近的位置时,通常意味着您正试图通过 NULL 指针访问成员变量。由于位置是 0x4,因此该成员的偏移量可能是从对象开始的 4。

你唯一struct拥有的是这个:

struct node{
int value;
struct node *link;
};

在这里,value偏移量为 0x0,link偏移量为 0x4,因此错误将出现在您尝试link通过 NULL 指针访问成员的地方。

于 2012-08-27T21:54:06.987 回答