我正在创建一个以链表的形式在内存中加载文件的函数。但是当我编译代码时,错误就出现了:error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’
代码在
之下load_file.c:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node{
char* data = NULL;
struct node* next = NULL;
};
struct node* head = NULL;
struct node* tail = NULL;
int load_file(char* file_name){
char line[1000];
char* data = NULL;
struct node* temp = NULL;
FILE* fp = fopen(file_name,"r");
if(fp == NULL){
printf("cannot open the file\n");
return -1;
}
while(fscanf(fp,"%99s",line) == 1){
data = (char*)malloc(sizeof(char) * strlen(line));
if(data == NULL){
printf("could not allocate memory for string\n");
return -2;
}
strcpy(data,line);
temp = (struct node*)malloc(sizeof(struct node));
if(temp == NULL){
printf("could not allocate memory for node\n");
}
if(head == NULL){
head = temp;
tail = temp;
}else{
tail->next = temp;
tail = tail->next;
}
}
return 0;
}
load_file.h:
int load_file(char*);
test.c的:
#include<stdio.h>
#include"load_file.h"
int main(){
char* file= "text.txt";
printf("ruuning\n");
load_file(file);
printf("done");
return 0;
}
编译错误时:
harsh@harsh-Inspiron-3558:~/c/bank_management/include/load_file$ sudo gcc test.c load_file.c -o test
load_file.c:6:13: error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token
char* data = NULL;
^
load_file.c: In function ‘load_file’:
load_file.c:42:8: error: ‘struct node’ has no member named ‘next’
tail->next = temp;
^
load_file.c:43:15: error: ‘struct node’ has no member named ‘next’
tail = tail->next;
^
对于任何错误抱歉。我是初学者。
答案 0 :(得分:2)
C结构没有成员的默认值。从结构定义中删除= NULL
。如果您希望最初将值清零,请使用calloc
而不是malloc
分配结构,或者如果它是堆栈或全局变量(不是堆分配),则将其声明/初始化为{{1 }}
答案 1 :(得分:2)
您不会在类型定义中添加初始值设定项;变化
struct node{
char* data = NULL;
struct node* next = NULL;
};
到
struct node{
char *data;
struct node *next;
};
您在创建struct node
的实例时初始化这些字段,如下所示:
struct node foo = {NULL, NULL};
或
struct node foo = { .data = NULL, .next = NULL }; // as of C99
或
struct node foo;
...
foo.data = NULL;
foo.next = NULL;
或
struct node foo;
...
foo = (struct node){.data = NULL, .next = NULL}; // as of C99
或
struct node *foo = malloc( sizeof *foo );
foo->data = NULL;
foo->next = NULL;
或
struct node *foo = malloc( sizeof *foo );
*foo = (struct node){.data = NULL, .next = NULL}; // as of C99
请注意,
时struct node *foo = calloc( 1, sizeof *foo );
会将*foo
的字段初始化为所有位0,这与将它们初始化为NULL
不一定相同 - 所有保证的是零值常量表达式等同于NULL
,而不是零值运行时表达式。