无法访问内存地址

无法访问内存地址

我正在尝试读取文件的每一行并插入到链表中,但是当将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;


当我调试代码时,在监视表上,insertFirst函数的参数char * name显示如下:错误无法访问内存地址0x3847aef1

最佳答案

首先检查fopen()的返回值是否成功。打开fopen()的手册页。例如

f1 = fopen("text.txt", "r");
if(f1 == NULL ) {
        fprintf(stderr,"file doesn't exist \n");
        return 0;
}


其次,在http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong处读取feof()错误的原因,而不是检查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;
}

10-04 10:18