Search code examples
cpointersstructdereference

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


This is the error:

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

And this is the code:

#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;
}

Solution

  • You defined struct inv inside of your main function. As a result, it's not visible outside of main. This means that the struct inv mentioned in the declaration of the funciton values is a different struct, and one that hasn't been fully defined yet. That's why you're getting the "incomplete type" error.

    You need to move the definition outside of the function.

    Also, the type of t->a is int, but you're assigning it an int *. Get rid of the address-of operator here and assign the value of w directly.

    #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;
    }