c - 解引用指向不完整类型的指针 - 使用指向函数的指针将值分配给结构

标签 c pointers struct dereference

这是错误:

str.c: In function ‘values’: str.c:15:3: error: dereferencing pointer to incomplete type ‘struct inv’
     t -> a = &w;

这是代码:

#include<stdio.h>

void values(struct inv *t, int , float);

void main()
{
    struct inv {
        int a;
        float *p;
    } ptr;
    int z = 10;
    float x = 67.67;
    values(&ptr, z, x);
    printf("%d\n%.2f\n", ptr.a, *ptr.p);
}

void values(struct inv *t, int w , float b) {
    t -> a = &w; /* I am getting error here, not able to assign value 
                     using the arrow operator */
    t -> p = &b;
}

最佳答案

您在 main 函数中定义了 struct inv 。因此,它在 main 之外不可见。这意味着函数 values 声明中提到的 struct inv 是一种不同的结构,并且尚未完全定义。这就是您收到“类型不完整”错误的原因。

您需要将定义移到函数之外。

此外,t->a 的类型是 int,但您为其分配了 int *。这里去掉取址运算符,直接给w赋值。

#include<stdio.h>

struct inv {
    int a;
    float *p;
};

void values(struct inv *t, int , float);

void main()
{
    struct inv ptr;
    int z = 10;
    float x = 67.67;
    values(&ptr, z, x);
    printf("%d\n%.2f\n", ptr.a, *ptr.p);
}

void values(struct inv *t, int w , float b) {
    t -> a = w; 
    t -> p = &b;
}

关于c - 解引用指向不完整类型的指针 - 使用指向函数的指针将值分配给结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43415922/

相关文章:

C 函数和 NaN

c - 如何在结构内复制到结构内的缓冲区

c - uint32_t 和其他 stdint 类型的 atoi 或 strtoul 等价物是什么?

c++ - std::cout 不打印到控制台

c++ - NULL 指针问题?

c++ - 防止简单的宏替换

c - C 中返回指针的函数

c - C 中对 <symbol> 的未解析引用。Makefile 似乎顺序为 : gcc command is perfectly fine according to the suggestions

xcode - 在调试期间检查 Swift 中的结构不起作用

c++ - 二叉搜索树,分配指向模板化结构节点的指针