I am trying to do the following, it does not give me compilation error but gives me a segmentation fault when I run this.
int main(){
int * ptr;
*ptr = 254;
char **ch = (char **)ptr;
printf("\n%x\n",**ch);
}
I basically want to know if something like this is legal, and if so what it does.
*(char **)ptr
where ptr is either of type int or type void
*ptr = 254;
here ptr
is not allocated memory, that's why producing segmentation fault.
First you need to allocate the memory to ptr
, then you can put some value into *ptr
.
Next, *(char **)ptr
is not legal (neither is char **ch = (char **)ptr;
, BTW). If you compile with warnings enabled, you'll get some warning message
warning: initialization from incompatible pointer type
You can easlity understand this if you try to analyze the data type of either variables. Consider a 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 you compile and step through a debugger, you 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 at address 0x57e58955
The variable ptr is uninitialized.
A pointer is a variable which stores address.
Here the variable ptr is not initialized to any value.
When it tries to access ptr it crashes for sure.
Because ptr has a junk address value, and you are trying to access that.
With the given code, that must be the issue.
But the issue is not with the type conversion to char**.
Few things needs to be set right in your code:
Take a look at the below code: Let's say you assign some memory dynamically using malloc or use a pointer to point to some location as shown below.
#include<stdio.h>
#include<string.h>
int main(){
int a =10;
int * ptr = &a;
*ptr = 81;/* ASCII value of Q is 81 */
printf("%d\n",a);
char **ch = (char **)&ptr;/* Pointer pointing to a pointer */
printf("%c\n",**ch);/* You will see Q getting printed */
/* Now if you want to modify the value of a it can be done */
**ch = 'R';
printf("%d\n",a); /* The value stored in a will be 82 ASCII value of R */
printf("%c\n",**ch);
printf("%d\n",**ch); /* You should get 82 here */
/* Now lets say you try to set a to value 290 */
a = 290;
printf("%d\n",a);/* You get 290 here */
printf("%d\n",**ch); /* Sorry you won't get 290 here */
printf("%c\n",**ch);
/* Since only 1 byte is what char pointer can access you get equivalent ASCII value for the value matching 8 bits */
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.