【发布时间】:2015-02-07 08:05:35
【问题描述】:
我正在尝试编写一个函数,该函数可以将文件中的一些信息读取到双向链表中的节点中。每个节点数据的格式如下。
结构(命名记录)
艺术家
专辑
歌曲
流派
songLength(这是另一个包含分钟和秒的结构)
播放次数
评分
void load(FILE *file, Node *head)
{
char tempArtist='\0', tempAlbum='\0', tempTitle='\0', tempGenre='\0'
,tempSpace='\0',tempMins='\0',tempSecs='\0';
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;
制作节点
Node *makeNode(Record *newData)
{
Node *temp = NULL;
temp=(Node*)malloc(sizeof(Node));
temp->data=newData;
temp->pNext=NULL;
return temp;
}
如果出现任何混淆,请告诉我! 这也是我第一次体验动态记忆,所以要温柔:P
谢谢!
【问题讨论】:
-
当你使用动态内存时,你需要明确地
malloc它。当您将tempLength声明为指针然后从不为其分配任何内存时,您遇到了问题。 -
@SimonGibbons 初始化头节点时是否尚未分配内存? (主要发生)
-
是的可能(但我看不到该代码)但是当您执行
tempLength->mins=tempMins;时,您使用的是tempLength,它对您之前为该结构分配的任何内存一无所知。 -
那么我该如何为我的节点分配内存呢?由于在节点内还有另一个结构,记录。我将在上面包含我的 make 节点函数。
标签: c linked-list