I'm required to allocate memory of 5 bytes. I do it like:
uint16_t* memory = (uint16_t*) malloc(5);
My question is how to store different types to that memory and print it. specifically I need 3x char, 1x float, and 1x int.
CodePudding user response:
Without wider context about the assignment it is not possible to determine the solution your tutor is looking for, but to be clear malloc()
returns a void pointer to memory guaranteed to be aligned in a manner that can be interpreted as any fundamental type.
The use of uint16_t
here seems rather arbitrary, and is presumably chosen to test you knowledge of pointer concepts and type casts. The strange choice of 5 byte length may also be contrived to highlight the fact that the space need only be large enough to hold the largest object to be stored.
This appears to be one of those tasks beloved of school assignments that do not necessarily encourage good coding practice. That said, the following 'dirty' solution may be what is sought:
uint16_t* memory = (uint16_t*) malloc(5);
char* c = (char*)memory ;
c[0] = 'a' ;
c[1] = 'b' ;
c[2] = 'c' ;
float* f = (float*)memory ;
*f = 1.0 ;
int* i = (int*)memory ;
*i = 123 ;
A more sophisticated solution, that may be stepping beyond your course material is to use a union:
union
{
uint16_t s ;
char c[3] ;
float f ;
int i ;
}* memory = malloc( sizeof( *memory ) ) ;
memory->c[0] = 'a' ;
memory->c[1] = 'b' ;
memory->c[2] = 'c' ;
memory->f = 1.23 ;
memory->i = 123 ;
If the specific allocation line is "required" then you can use a named union and cast memory
:
uint16_t* memory = malloc(5);
union variant
{
char c[3] ;
float f ;
int i ;
} ;
((union variant*)memory)->f = 1.23 ;
((union variant*)memory)->i = 123 ;
((union variant*)memory)->c[0] = 'a' ;
((union variant*)memory)->c[1] = 'b' ;
((union variant*)memory)->c[2] = 'c' ;