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

C 未保存数组结构的特定元素,c,struct,scanf,C,Struct,Scanf,我试图将文件中的名字、姓氏和数字扫描到结构数组中。当我将数据存储到数组中时,除了 临时工[1]。姓氏 我不明白为什么它拒绝在数组的这个元素中插入姓氏&任何通知

我试图将文件中的名字、姓氏和数字扫描到结构数组中。当我将数据存储到数组中时,除了 临时工[1]。姓氏

我不明白为什么它拒绝在数组的这个元素中插入姓氏&任何通知<

这是结构

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,但是除了姓氏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));
但您必须为
大小
项目分配,以避免写越界:

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

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

调用
malloc
,您将分配多少个结构?此外,您何时何地读取“大小”?为什么要在
中将
作为参数传递,而不是在函数内部局部定义它?哦,请阅读抱歉,刚刚更新了我在主函数中定义了变量大小。我将它作为一个参数传递,而不是在函数中定义它,因为在我正在处理的项目中,我还需要在多个部分使用此变量。您从不检查
fscanf
temp = (KBLottoPlayer*)malloc(sizeof(KBLottoPlayer) * size);