【发布时间】:2012-09-09 14:38:08
【问题描述】:
在这段代码中,我试图创建一个列表,其中包含来自输入文件的所有字符,我的主要问题是句子“你不能返回函数的局部变量”Iv'e被告知这让我很困惑。我动态分配了一个 List 并返回它,我可以只定义 List list 而不使用动态分配并返回它吗?我相信这是错误的,因为所有信息都会被自动删除,我只剩下我创建的原始列表的地址。
这里是更多信息的代码:
typedef struct Item {
char tav;
struct Item* next;
} Item;
typedef struct List {
Item* head;
} List;
List* create(char* path) {
FILE* file;
List* list;
Item* trav;
Item* curr;
char c;
file=fopen(path, "r");
if (file==NULL) {
printf("The file's not found");
assert(0);
}
if (fscanf(file, "%c", &c)!=1) {
printf("The file is empty");
assert(0);
}
trav=(Item *)calloc(1, sizeof(Item));
trav->tav=c;
list=(List *)calloc(1, sizeof(List)); /* allocating dynamiclly the list so it won't be lost at the end of the function*/
list->head=trav;
while (fscanf(file, "%c", &c)==1) {
curr=(Item*)calloc(1, sizeof(Item));
curr->tav=c;
trav->next=curr;
trav=curr;
}
trav->next=NULL;
fclose(file);
return list;
}
我说的对吗?这是必要的吗?我可以定义 List 而不是一个指向一个返回它的指针吗?
【问题讨论】: