我正在制作一个函数,以链表的形式将文件加载到内存中。但是当我编译代码时,出现错误: error: Expected ':', ',', ';', '}' 或 '__attribute__'
代码如下
加载文件.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;
}
加载文件.h:
int load_file(char*);
测试.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;
^
对于任何错误,我们深表歉意。我是初学者。
最佳答案
您无需将初始值设定项添加到类型定义中;改变
struct node{
char* data = NULL;
struct node* next = NULL;
};
至
struct node{
char *data;
struct node *next;
};
当您创建结构节点
的实例时,您将初始化这些字段,如下所示:
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
相同 - 所保证的是零值< em>常量表达式相当于NULL
,而不是零值运行时表达式。
关于c - 错误 : expected ‘:’ , ‘,’、 ‘;’、 ‘}’ 或 ‘__attribute__’,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42749395/