gpt4 book ai didi

c - 为结构指针赋值

转载 作者:太空宇宙 更新时间:2023-11-04 05:23:08 25 4
gpt4 key购买 nike

我正在尝试为 my_record 赋值,但编译器一直指示我的行 my_record->x = counter; 有错误:

uninitialized local variable 'my_record' used.

#include<stdio.h>

typedef struct rec
{
int x, y, z;
} *abc;

int main()
{
int counter;
FILE *ptr_myfile;
//struct rec my_record;
abc my_record;

ptr_myfile = fopen("test.bin", "wb");
if (!ptr_myfile)
{
printf("Unable to open file!");
return 1;
}
for (counter = 1; counter <= 10; counter++)
{
my_record->x = counter;
fwrite(&my_record, sizeof(abc), 1, ptr_myfile);
}
fclose(ptr_myfile);
system("pause");
system("pause");
return 0;
}

最佳答案

你有几个问题。

首先,您没有为my_record 分配内存指向。关于使用未初始化变量的警告是因为你没有这样做:

abc my_record = malloc(sizeof(struct rec));

其次,fwrite() 的第一个参数应该是指向您要写入的结构的指针,但您使用的是指向该指针的指针。

第三,fwrite() 的第二个参数应该是结构的大小,但您给出的是指针的大小。

一开始似乎没有什么好的理由将 abc 定义为指针。您应该只声​​明一个包含结构本身的变量。

#include<stdio.h>

typedef struct rec
{
int x, y, z;
} abc;

int main()
{
int counter;
FILE *ptr_myfile;
//struct rec my_record;
abc my_record;

ptr_myfile = fopen("test.bin", "wb");
if (!ptr_myfile)
{
printf("Unable to open file!");
return 1;
}
for (counter = 1; counter <= 10; counter++)
{
my_record.x = counter;
fwrite(&my_record, sizeof my_record, 1, ptr_myfile);
}
fclose(ptr_myfile);
system("pause");
return 0;
}

关于c - 为结构指针赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50843188/

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