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

dereferencing pointer to incomplete type - assigning values to struct using pointer to a function

这是错误:

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 是一个不同的结构,并且尚未完全定义。这就是您收到 "incomplete type" 错误的原因。

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

此外,t->a 的类型是 int,但您将其指定为 int *。这里去掉address-of操作符,直接给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;
}