【发布时间】:2022-01-13 01:31:41
【问题描述】:
我试图扫描文件并将数据添加到链接列表中,然后将操作打印到输出文件中。我成功将操作打印到输出文件,但是当我尝试访问它时,我的链接列表的内容是空的。
然后我检查创建和链接的每个节点的地址,发现没有问题,当它在函数内部时,链接列表工作正常,但在 main() 中没有。
输入.txt
3
1 编码标记编程
1 烹饪米妮烹饪
1 园艺一分钱植物学
此代码未完成,但包含我的问题:
#include<stdio.h>
#include<ctype.h>
#include<string.h>
struct book {
char *title;
char *author;
char *subject;
};
struct library {
struct book collection;
int num_books;
struct library *next;
};
void AddBook(FILE *IF, FILE *OF, struct library** thislib);//function prototype
int main(void){
FILE *IF,*OF;
int sel,numOp,i;
struct library *Lib=NULL;//declare head pointer
if(((IF=fopen("library.txt","a+"))==NULL)||((OF=fopen("output.txt","w"))==NULL)){//open input and output file
printf("File cannot be open!");
}
else{
fscanf(IF," %d",&numOp); //scan the number of operation from file
for(i=0;i<numOp;i++){ //Loop according to number of operation
if(feof(IF)) //if file pointer reach EOF break
break;
fscanf(IF," %d",&sel); //scan the type of operation
switch(sel){
case 1:
AddBook(IF,OF,&Lib); //add the book if sel is 1
break;
case 2:
break;
}
printf("%s ", Lib->collection.title); // print the title of the book but it show nothing
}
}
return 0;
}
void AddBook(FILE *IF, FILE *OF, struct library** thislib){
char title[30],author[30],subject[20]; //declare variable to hold data
struct library *temp=NULL; //create a new node
struct library *ptr=*thislib; //create a pointer that point to head of link list
temp=(struct library*)malloc(sizeof(struct library)); //allocate memory for the new node
fscanf(IF," %s %s %s" ,title,author,subject);
temp->collection.title=title; // put the data into link list
temp->collection.author=author;
temp->collection.subject=subject;
temp->next=NULL;
if((*thislib)==NULL){
(*thislib)=temp; // if there is no content in link list put temp into head
}
else{
while (ptr->next!=NULL)
{
ptr=ptr->next; //put node at the end of link list
}
ptr->next=temp;
}
fprintf(OF,"The book %s author %s subject %s has been added to the library.\n",title,author,subject);
printf("%s ",(*thislib)->collection.title); //this work fine but it keep updating, weren't it suppose to have the same value
}
【问题讨论】:
-
temp->collection.title=title;将指向局部变量的指针放入列表节点。当函数返回时,这些指针变得无效。您需要制作字符串的动态副本,例如temp->collection.title=strdup(title) -
嘿,它的工作非常感谢你,strcpy() 也工作吗?
-
在分配内存之前不能使用
strcpy()。strdup()是malloc()和strcpy()的组合。
标签: c function linked-list scanf