Why do I get a warning here? How can I fix this?
memUnit * newUnit = (char*) freeUnit sizeof(memUnit);
I want to allocate a new Unit after the old Unit in my Memory (basically DIY calloc()). All variables with the word Unit in it are all of the struct memUnit.
Everything works fine like this, but how do I fix the warning?
CodePudding user response:
You're trying to assign a char *
into a memUnit *
.
Now, I don't know what memUnit
is in this context, but if it's larger than a single-byte value, you're assigning a byte-aligned pointer into a (something larger)-aligned pointer, and the compiler has every reason to complain. I'm assuming that's the problem.
If freeUnit
is declared as memUnit *
, you don't need to cast the pointer type. Just use:
memUnit *newUnit = freeUnit 1;
or memUnit *newUnit = &freeUnit[1];
If freeUnit
is some other type, particularly one with a different size/alignment, you're on dangerous ground!
If it's a type with the exact same size as memUnit
, and you have checked it's correctly aligned, you could cast it to memUnit *
and add one, as above.
CodePudding user response:
There is no implicit conversion from a pointer to the type char * to any other pointer to object type except the type void *.
So you need to write either
memUnit * newUnit = ( memUnit * )( (char*) freeUnit sizeof(memUnit) );
or
memUnit * newUnit = ( void * )( (char*) freeUnit sizeof(memUnit) );