Search code examples
cstructincomplete-type

invalid application of 'sizeof' to an incomplete type struct


this is a bit puzzling to me because it worked in the past.

I have a vector3 struct and a matrix4 struct which are defined like this

enter image description here

common_struct.h looks like this

struct {
    float m[16];
} mat4_scalar;

struct {
    float p[3];
} vector3_scalar;

then In my vector3_scalar.h I have functions like these:

#include "../../common/common_structs.h"

struct vector3_scalar* vec3_zero(void);
struct vector3_scalar* vec3_up(void);
struct vector3_scalar* vec3_right(void);
struct vector3_scalar* vec3_forward(void);

in my vector3_scalar.c I am trying to malloc a vector3_scalar like this:

#include "../headers/vector3_scalar.h"

struct vector3_scalar* v = (struct vector3_scalar*)malloc(sizeof(struct  vector3_scalar)); //<--- error occurs here

but I am getting invalid application of 'sizeof' to an incomplete type struct vector3_scalar

I've also tried including the common_structs.h directly in the .c file but that doesn't seem to help either.

What am I doing wrong in this situation?


Solution

  • struct {
        float p[3];
    } vector3_scalar;
    

    This declares a variable named vector3_scalar of type "unnamed struct". You want

    struct vector3_scalar {
        float p[3];
    };
    

    Better yet

    typedef struct {
        float p[3];
    } vector3_scalar;
    

    and then use just vector3_scalar (not struct vector3_scalar) everywhere.