我试图读取文件的每一行并插入链接列表,但是当将str [500]传递给函数时,没有访问内存地址,这是我的代码
char str[500];
FILE *f1;
f1 = fopen("text.txt", "r");
while (!feof (f1)){
fscanf (f1, "%s", str);
insertFirst(str);
}
fclose(f1);
printList();
这是我的链接列表插入代码
void insertFirst(char* name) {
struct node *link = (struct node*) malloc(sizeof(struct node));
strcpy(link->nodename,name);
link->next = head;
head = link;
}
我的链表结构
struct node {
char nodename[500];
struct node *next;
};
struct node *head = NULL;
struct node *current = NULL;
当我在watch表上调试代码时,insertFirst函数的参数 char * name 显示:错误无法访问内存地址0x3847aef1
答案 0 :(得分:0)
首先检查fopen()
的返回值是否成功。打开fopen()
的手册页。例如
f1 = fopen("text.txt", "r");
if(f1 == NULL ) {
fprintf(stderr,"file doesn't exist \n");
return 0;
}
其次,请在此处阅读feof()
错误的原因http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong而不是检查fscanf()
的返回值。例如
while (fscanf (f1, "%s", str) == 1) {
insertFirst(str);
}
也不需要对malloc
进行类型转换。这是示例代码
struct node {
char nodename[500];
struct node *next;
};
struct node *head = NULL;
struct node *current = NULL;
void insertFirst(char* name) {
struct node *link = malloc(sizeof(struct node)); /* create new node by dynamic memory */
strcpy(link->nodename,name); /* copy the data */
link->next = head;
head = link; /* update the head every time */
}
void printList(void) {
struct node *temp = head; /* assign head to temp & do operation, don't modify head here since head is declared globally */
while(temp) {
printf("name : %s \n",temp->nodename);
temp = temp->next;
}
}
int main(void) {
char str[500];
FILE *f1 = fopen("text.txt", "r");
if(f1 == NULL ) {
fprintf(stderr,"file doesn't exist \n");
return 0;
}
while (fscanf (f1, "%s", str) == 1) { /* it returns no of items readon success */
insertFirst(str);/* pass the str read from file to insertFirst() function */
}
fclose(f1);
printList();
return 0;
}