c - 为结构指针赋值

标签 c

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

相关文章:

c - 为什么 sendto() 返回 'Invalid argument' ?

c - 如何在 C 中将两个 32 位整数用作 64 位整数?

c - C 中的回文缺失字母问题

c - TCP 函数 recv() 不能在循环中工作

c - 为什么使用 fscanf 会导致应用程序崩溃?

C 多线程 : What is the advantage of a Read Lock (pthread_rwlock_rdlock) if all threads can access it simultaneously?

c++ - 使用 c++/vC++ 将结构数组和二维数组传递给函数

c++ - 如何通过代理将套接字连接到http服务器?

c++ - 递归函数不能内联吗?

c - 如何将二维数组的基地址赋给指针