【发布时间】:2016-11-14 21:00:15
【问题描述】:
好的,我对 C 很陌生,需要解释为什么会出现此错误:
“变量‘newFilm’有初始化但类型不完整”
任务是创建一个名为 film 的结构。然后将 .txt 文件中的数据传递到该结构中,并创建一个结构的链接列表,表示 .txt 中的所有数据
问题似乎是编译器错过了我为 struct newFilm 分配内存的点,我认为这是正确完成的
主文件中的代码:
char* t = (char*)malloc(sizeof(char*));
int y;
char* r = (char*)malloc(sizeof(char*));
char* g = (char*)malloc(sizeof(char*));
int rt;
double s;
List* list = newList();
//read pReadFile
char input[256];
//read characters from file being pointed at, and store into input
while( fgets( input, 256, pReadFile )) {
//scan each line with each variable separated by a comma
fscanf(pReadFile,"%s %d %s %s %d %d\n", t,y,r,g,rt,s);
struct Film newFilm = createFilm(t,y,r,g,rt,s); //ERROR OCCURS HERE
addToList(list, newFilm);
}
printList(list, pWriteFile);
这是来自 film.c 源文件的 createFilm 函数:
Film *createFilm(char *title, int year, char *rating,
char *genre, int runtime, double score){
Film *newFilm = (Film*)malloc(sizeof(Film));
// n.b. error checking to be added - to be added
title = (char*)malloc(sizeof(title));
newFilm->title = title;
newFilm->year = year;
rating = (char*)malloc(sizeof(rating));
newFilm->rating = rating;
genre = (char*)malloc(sizeof(genre));
newFilm->genre = genre;
newFilm->runtime = runtime;
newFilm->score = score;
return newFilm;
}
虽然我认为 addToList 函数没有任何问题,但我认为我会保留它,以便您有更好的上下文(在 database.h 文件中):
void addToList(List* list, struct Film* film){
Node *node = (Node*)malloc(sizeof(Node));
//Generates an error message and the program terminates if
//insufficient memory is available.
if (node == NULL){
fprintf(stderr, "Error: Unable to allocate memory in list_add()\n");
exit(EXIT_FAILURE);
}
//appends film to tail of linked list
node->film = film;
node->next = NULL;
if (list->last == NULL){
list->first = list->last = node;
}
else{
list->last = list->last->next = node;
}
}
提前致谢:)
【问题讨论】:
-
Here is the createFilm function from film.h header file...等等..什么? -
对不起,不是头文件。搞糊涂了。
-
让我们假设指针的大小是 4。
char* t = (char*)malloc(sizeof(char*));很奇怪。为什么要为t分配,它指向一个char数组,4字节?如果代码需要 100 个数组char,请使用char* t = malloc(100);
标签: c memory-management struct compiler-errors dynamic-memory-allocation