I've been doing some practicing in C with dynamic memory allocations and pointers. I tried printing out random variables to see how it all works.
It works printing out chars and ints but for some reason no matter what I try I can't print out the float value I desire.
I tried manually typing pi, I tried using the constant from math.h
. It prints out a huge totally random number and I am completely baffled as to why it doesn't work.
I tried printf("%f\n", (float) memory[3]))
and printf("%f\n", (float) *(float *)&memory[3]))
but it doesnt work.
uint16_t* rezerviraj(int sizeToAllocate){
uint16_t *reservedSpace = malloc(sizeToAllocate + 4 * sizeof(char) + sizeof(float) + sizeof(int32_t));
memset(reservedSpace, 23246, sizeToAllocate);
return reservedSpace;
}
void brisi(uint16_t* pomnilnik){
free(pomnilnik);
}
uint16_t* vstavi(uint16_t* memory){
*(char *)&memory[0] = 'X';
*(char *)&memory[1] = 'P';
*(char *)&memory[2] = 'O';
*(float *)&memory[3] = 3.141312;
*(int32_t *)&memory[4] = 23246;
*(char *)&memory[5] = '!';
return memory;
}
void print(uint16_t* pomnilnik){
printf("%c \n", (char) *(char *)&memory[0]);
printf("%c \n", (char) *(char *)&memory[1]);
printf("%c \n", (char) *(char *)&memory[2]);
printf("%f\n", (float) memory[3]);
printf("%d \n", memory[4]);
printf("%c \n", (char) *(char *)&memory[5]);
}
int main() {
uint16_t *test= (uint16_t*) rezerviraj(500);
test = vstavi(test);
print(test);
brisi(test);
return 0;
}