2

I want to allocate array of structure but I'm getting this error with GCC:

st.c: In function ‘main’:
st.c:20:4: error: incompatible types when assigning to type ‘struct employeeStruct’ from type ‘void *’ *sp=malloc(sizeof(struct productStruct)*n);

And this is my struct and pointer:

struct productStruct
{
        unsigned int ID;
        unsigned long int serialnumber;
        char name[40];
};

struct productStruct *sp;

And after getting n variable from user at main function:(Im getting error for this line)

*sp=malloc(sizeof(struct *productStruct)*n);

I don't know maybe this is type casting error but I could not fix it. Thanks for your attention

4
  • 4
    just sp=malloc(sizeof(struct *productStruct)*n); don't de'reference you'll be OK Commented Apr 11, 2018 at 11:38
  • sp is the pointer and *sp dereferenced pointer . Commented Apr 11, 2018 at 11:40
  • @Jean-FrançoisFabre I think he rather wants this: sp = malloc(sizeof(struct productStruct) * n) Commented Apr 11, 2018 at 11:45
  • yeah, just realized that strange stuff inside. even better: sp=malloc(sizeof(*sp)*n); so if type changes the malloc remains coherent Commented Apr 11, 2018 at 11:45

1 Answer 1

3

You have 2 errors:

Use sp not *sp and reserve the size of the struct, not the size of a pointer to the struct (if you really want an array of structs instead of pointers):

sp=malloc(sizeof(struct productStruct)*n);

Sign up to request clarification or add additional context in comments.

2 Comments

Less error prone to do: sp = malloc(sizeof *sp * n);
To be fair, I've always found sizeof struct type_t more readable, granted your way of doing it makes refactoring easier, due to the independence of the type name.