使用嵌套结构写入链接列表

时间:2015-02-07 08:05:36

标签: c linked-list

我正在尝试编写一个函数,可以将文件中的某些信息读入双向链表中的节点。每个节点数据的格式如下。

struct(命名记录)
艺术家
专辑
歌曲
流派
songLength(这是另一个包含分钟和秒的结构)
playcount
评级

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;

makeNode

Node *makeNode(Record *newData)
{
    Node *temp = NULL;

    temp=(Node*)malloc(sizeof(Node));

    temp->data=newData;
    temp->pNext=NULL;

    return temp;
}

如果出现任何混淆,请告诉我! 这也是我对动态记忆的第一次体验,所以要温柔:P

谢谢!

2 个答案:

答案 0 :(得分:2)

这些行不对。

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 = '\0';
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.

我希望能为您提供有关如何更改变量的足够线索。

答案 1 :(得分:1)

您没有为变量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