C Pointer casting: single int pointer to double char pointer -
i trying following, not give me compilation error gives me segmentation fault when run this.
int main(){ int * ptr; *ptr = 254; char **ch = (char **)ptr; printf("\n%x\n",**ch); }
i want know if legal, , if does.
*(char **)ptr
where ptr either of type int or type void
*ptr = 254;
here ptr
not allocated memory, that's why producing segmentation fault.
first need allocate memory ptr
, can set value *ptr
.
next, *(char **)ptr
not legal (neither char **ch = (char **)ptr;
, btw). if compile warnings enabled, you'll warning message
warning: initialization incompatible pointer type
you can easlity understand if seek analyze info type of either variables. consider sample code
#include <stdio.h> #include <stdlib.h> int main(){ int * ptr = malloc(4); *ptr = 254; char **ch = (char **)ptr; printf("\n%x\n",**ch); }
to check, if compile , step through debugger, can see,
5 int * ptr = malloc(4); (gdb) s 6 *ptr = 254; (gdb) 7 char **ch = (char **)ptr; (gdb) p ptr $1 = (int *) 0x804a008 (gdb) p ch $2 = (char **) 0xa7c600 (gdb) p *ch $3 = 0x57e58955 <address 0x57e58955 out of bounds> (gdb) p **ch cannot access memory @ address 0x57e58955
c pointers
No comments:
Post a Comment