从文件读入一些数据后,将其分配给节点内的结构类型记录,数据与文件的数据匹配。在我离开读取功能并返回主要数据后,数据仍然保持不变。但是当我试图打印它时,它就变成了乱七八糟的混乱。
加载功能
void load(FILE *file, Node *head)
{
char tempArtist[30]={'\0'}, tempAlbum[30]={'\0'}, tempTitle[30]={'\0'}, tempGenre[30]={'\0'},tempSpace='\0';
SongLength *tempLength=NULL;
int tempPlay=0, tempRating=0, tempMins=0, tempSecs=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,"%c",&tempSpace);
tempLength->mins=&tempMins;
tempLength->secs=&tempSecs;
head->data->album=tempAlbum;
head->data->artist=tempArtist;
head->data->genre=tempGenre;
head->data->song=tempTitle;
head->data->length=tempLength;
head->data->played=tempPlay;
head->data->rating=tempRating;
}
打印测试功能
int main(void)
{
FILE *loadFile = NULL;
Node *head=NULL;
head=(Node*)malloc(sizeof(Node));
head->data=(Record*)malloc(sizeof(Record));
head->data->length=(SongLength*)malloc(sizeof(SongLength));
loadFile=fopen("records.txt","r");
load(loadFile,head);
head->data->artist; // artist matches the name in load file (aka snoop)
printf("%s", head->data->artist); // When trying to print here it prints a smiley face
}
易于复制的额外信息
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 record *data;
struct node *pNext;
}Node;
文件数据格式
snoop
heartbeat
swiggity
rap
03
10
25
4
答案 0 :(得分:0)
您有undefined behavior,因为您将指向本地数组的指针分配给head
结构。
例如,一旦函数tempArtist
返回,数组load
将超出范围,因此任何指向该数组的指针(如head->artist
)将是迷路指针,并且去除那些指针将导致所述未定义的行为。