我正在尝试为 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/