gpt4 book ai didi

c - 数组结构的特定元素未保存

转载 作者:行者123 更新时间:2023-11-30 14:42:43 25 4
gpt4 key购买 nike

我正在尝试将文件中的名字、姓氏和号码扫描到结构数组中。当我将数据存储到数组时,每个元素都工作正常,除了临时[1].lastName

我不明白为什么它拒绝将姓氏插入数组的这个元素中任何建议<

这是结构

typedef struct
{
char firstName [20];
char lastName [20];
int numbers[6];
}KBLottoPlayer;

这是我声明变量大小的地方

int i,size;
FILE *in = fopen("KnightsBall.in","r");
fscanf(in,"%d",&size);

这是我将文件中的信息存储到数组中的函数

KBLottoPlayer* readArray(FILE* in, int size)
{

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

int i;
if((in = fopen("KnightsBall.in", "r")) != NULL )
{
char buffer[100];
fgets(buffer, 5, in);
for(i=0;i<size;i++)
{
fscanf(in,"%s ", temp[i].firstName);
fscanf(in,"%s ", temp[i].lastName);
fscanf(in,"%d %d %d %d %d %d ", &temp[i].numbers[0], &temp[i].numbers[1], &temp[i].numbers[2], &temp[i].numbers[3], &temp[i].numbers[4], &temp[i].numbers[5]);
printf("%s %s %d %d %d %d %d %d\n ",temp[i].firstName, temp[i].lastName, temp[i].numbers[0], temp[i].numbers[1], temp[i].numbers[2], temp[i].numbers[3], temp[i].numbers[4], temp[i].numbers[5]);
}
}
else
{
printf("File is Not Exist.\n");
}

return temp;
}

这是输入文件:

10
Llewellyn Mark
1 15 19 26 33 46
Ethan Willingham
17 19 33 34 46 47
Cazalas Jonathan
1 4 9 16 25 36
Siu Max
17 19 34 46 47 48
Balci Murat
5 10 17 19 34 47
Young Bryan
1 2 3 4 5 6
Anna Farach
1 3 5 7 9 10
Justin Mills
2 4 5 6 7 8
Tony Rose
1 3 4 5 6 7
Jess Jones
3 4 5 6 7 8

我希望输出是精确的列表,除了没有 10 之外,但除了姓氏 Willingham 之外,所有内容都会正常打印。

实际输出:

Llewellyn Mark 1 15 19 26 33 46
Ethan 17 19 33 34 46 47
Cazalas Jonathan 1 4 9 16 25 36
Siu Max 17 19 34 46 47 48
Balci Murat 5 10 17 19 34 47
Young Bryan 1 2 3 4 5 6
Anna Farach 1 3 5 7 9 10
Justin Mills 2 4 5 6 7 8
Tony Rose 1 3 4 5 6 7
Jess Jones 3 4 5 6 7 8

按任意键继续。 。 .

最佳答案

您需要为要读取的结构数量分配足够的空间。目前您仅在此处分配单个项目:

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

但您必须分配 size 项以避免写入越界:

temp = (KBLottoPlayer*)malloc(sizeof(KBLottoPlayer) * size);

否则您会观察到未定义的行为。

关于c - 数组结构的特定元素未保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54346837/

25 4 0
文章推荐: c# - connectionstring 和 entityframework 的问题
文章推荐: javascript - 在 ReactJS 中将类名添加到
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com