我正在尝试编写一个函数,该函数可以将文件中的一些信息读取到双链表中的节点中。每个节点数据的格式如下。
结构(命名记录)
艺术家
相册
歌曲
流派
songLength(这是另一个包含分钟和秒的结构)
播放次数
评级
void load(FILE *file, Node *head)
{
char tempArtist=' ', tempAlbum=' ', tempTitle=' ', tempGenre=' '
,tempSpace=' ',tempMins=' ',tempSecs=' ';
SongLength *tempLength=NULL;
int tempPlay=0, tempRating=0,test=0;
tempLength = (SongLength*)malloc(sizeof(SongLength));
fscanf(file,"%s",&tempArtist);
fscanf(file,"%s",&tempAlbum);
fscanf(file,"%s",&tempTitle);
fscanf(file,"%s",&tempGenre);
fscanf(file,"%s",&tempMins);
fscanf(file,"%s",&tempSecs);
fscanf(file,"%s",&tempPlay);
fscanf(file,"%s",&tempRating);
fscanf(file,"%s",&tempSpace);
tempLength->mins=tempMins;
tempLength->secs=tempSecs;
head->data->album=tempAlbum; // breaks here
head->data->artist=tempArtist;
head->data->genre=tempGenre;
head->data->song=tempTitle;
head->data->length=tempLength;
head->data->played=tempPlay;
head->data->rating=tempRating;
}
这是我当前的负载函数。当试图将这些值存储到节点数据中时,我会遇到访问冲突。
以下是我的结构,便于复制
typedef struct songlength
{
int mins;
int secs;
}SongLength;
typedef struct record
{
char artist;
char album;
char song;
char genre;
struct songlength *length;
int played;
int rating;
}Record;
typedef struct node
{
struct node *pPrev;
struct node *pNext;
struct record *data;
}Node;
makeNode
Node *makeNode(Record *newData)
{
Node *temp = NULL;
temp=(Node*)malloc(sizeof(Node));
temp->data=newData;
temp->pNext=NULL;
return temp;
}
如果有任何困惑,请告诉我!这也是我第一次体验动态记忆,所以要温柔:P
谢谢!
这些行不正确。
fscanf(file,"%s",&tempArtist);
fscanf(file,"%s",&tempAlbum);
fscanf(file,"%s",&tempTitle);
fscanf(file,"%s",&tempGenre);
fscanf(file,"%s",&tempMins);
fscanf(file,"%s",&tempSecs);
fscanf(file,"%s",&tempPlay);
fscanf(file,"%s",&tempRating);
fscanf(file,"%s",&tempSpace);
由于变量的定义方式,它们肯定会导致未定义的行为。
你不能指望
char c = ' ';
fscanf(file, "%s", &c);
工作。&c
的内存不足,无法读取字符串。你需要这样的东西:
char s[100]; // Or some size that is large enough to hold the data
// you are about to read.
fscanf(file, "%99s", s); // Make sure that you don't read more than 99
// characters. Leave at least one character
// for the terminating null character.
我希望这能给你足够的线索来改变你的变量。
您没有为要指向的变量tempLength
分配内存。
在访问元素之前添加此项
SongLength *tempLength = malloc(sizeof(struct(SongLength));
编辑
我只是给出了一个如何为您的案例分配和使用嵌套结构的总体想法
Node *head;
Record *r=malloc(sizeof(struct record));
SongLength *s=malloc(sizeof(struct songlength));
r->length=s;//<----- 1
r->length->mins=10;//Now you can assign values
head=malloc(sizeof(struct node));
head->pPrev=NULL;
head->pNext=NULL;
head->data=r;//<--- The length member inside record is already assigned memory in 1
head->data->artist='c';
head->data->length->mins=10;//assign