gpt4 book ai didi

c - printf 期间数据被修改

转载 作者:行者123 更新时间:2023-11-30 17:21:07 25 4
gpt4 key购买 nike

从文件中读取一些数据后,将其分配给节点内的结构类型记录,数据与文件的数据匹配。在我离开读取功能并返回主程序后,数据仍然保持不变。但当我尝试打印它时,它变得一团糟。

加载函数

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

最佳答案

您有undefined behavior因为您将指向本地数组的指针分配给 head 结构。

例如,一旦函数 load 返回,数组 tempArtist超出范围,因此任何指向该数组的指针(例如head->artist)将是杂散指针,取消引用这些指针将导致上述未定义的行为。

关于c - printf 期间数据被修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28389455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com