#include <stdio.h>
int main () {
char c = 'A';
int *int_ptr;
double *double_ptr;
*int_ptr = *(int *)&c;
*double_ptr = *(double *)&c;
printf("Original char = %c \n", c);
printf("Integer pointer = %d \n", *int_ptr);
printf("Double pointer = %f\n", *double_ptr);
return 0;
}
The questing is – Why can't I assign the double_ptr using this code, because it causes segmentation fault, but works fine for integer?
As I understand char is 1-byte long and int is 4-bytes long, so double is 8 bytes-long.
By using expression *(double *)&c I expect the following:
- & – Get the memory address of c.
- (double *) – pretend that this is a pointer to double.
- *() – get the actual value and assign it to double var.
*int_ptris addressing memory that doesn't belong to you, i.e. UB. You don't even know where as the pointer is uninitialized. Besides that you try to read a char (1 byte) using int (4 or 8 bytes) which again is UB. - 4386427