2012-01-27 87 views
0

我从文件存储中读取数据到列表中;链接列表-1将节点添加到前面

我要添加到列表的前面,我读了。

插入似乎工作,但我的打印功能产生-1回报。 这是我的代码:

#include <stdio.h> 
#include <stdlib.h> 

这是我的名单

typedef struct node{ 
int x,y,v; 
struct node* next; 
}node; 

这是我的插入:

node* insert(node* L, int x, int y, int v){ 
node* new= (node*)malloc(sizeof(node*)); 
new->x = x; 
new->y = y; 
new->v = v; 
new->next=NULL; 
if(L==NULL){ 
    L=new; 
} 
else{ 
new->next=L; 
L=new; 
} 
return L; 
} 

这个问题似乎是在这里:

void printList(node* L){ 
node* c=NULL; 
c=L; 
while(c != NULL){ 
printf("x=%d, y=%d, v=%d\n", c->x, c->y, c->v); 
c=c->next; 
} 
} 

主要的:

int main(int argc, char* argv[]){ 
FILE* in; 
int h, w; 
int x, y, v; 
in = fopen(argv[1], "r"); 
if(in == NULL) 
    { 
      puts ("cannot open file") ; 
      exit(0) ; 
    } 
fscanf (in, "%d,%d\n", &h, &w); 
printf("%d,%d\n", h, w); 
node* L=NULL; 
while(!feof (in)){ 
    fscanf (in, "%d,%d,%d\n", &x, &y, &v); 
    L=insert(L, x, y, v); 
    //printf("x=%d, y=%d, v=%d\n", L->x, L->y, L->v); 
    //printf("%d,%d,%d\n", x, y, v); 
} 

printList(L); 
return 0; 
} 

请问有什么不对?

回答

4
node* new= (node*)malloc(sizeof(node*)); 

你的指针node(32位机上的4个字节)分配的大小,但你想要的是一个节点(16个字节,或sizeof(node))。

而且,我会说,即使C不关心,我会避免new作为变量名。这是在许多语言中的关键字,

+0

用于'new'关键字的+1 – ouah 2012-01-27 19:30:25

2

甚至没有经过你的代码跟踪,我看到一个问题。您的malloc()的节点大小错误。它应该是sizeof(node)而不是sizeof(node*)(或者您可以使用sizeof(*new))。

直到你解决这个问题,这是不值得过的休息去,因为你会被捣毁内存。

+0

它的工作..我从来没有猜到这个问题在那里。谢谢! – 2012-01-27 19:28:24