[英]C Pointer casting: single int pointer to double char pointer
我正在嘗試執行以下操作,它不會給我編譯錯誤,但是在運行此命令時卻出現分段錯誤。
int main(){
int * ptr;
*ptr = 254;
char **ch = (char **)ptr;
printf("\n%x\n",**ch);
}
我基本上想知道這樣的事情是否合法,如果可以,它會做什么。
*(char **)ptr
其中ptr是int類型或void類型
*ptr = 254;
這里沒有為ptr
分配內存,這就是產生分段錯誤的原因。
首先,您需要將內存分配給ptr
,然后可以將一些值放入*ptr
。
接下來, *(char **)ptr
不合法( char **ch = (char **)ptr;
BTW也不合法)。 如果您在啟用警告的情況下進行編譯,則會收到一些警告消息
警告:從不兼容的指針類型初始化
如果您嘗試分析兩個變量的數據類型,就可以輕松理解這一點。 考慮一個示例代碼
#include <stdio.h>
#include <stdlib.h>
int main(){
int * ptr = malloc(4);
*ptr = 254;
char **ch = (char **)ptr;
printf("\n%x\n",**ch);
}
要檢查,如果您編譯並逐步調試,可以看到,
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
變量ptr未初始化。
指針是存儲地址的變量。
在這里,變量ptr沒有初始化為任何值。
當它嘗試訪問ptr時,肯定會崩潰。
因為ptr有一個垃圾地址值,所以您正在嘗試訪問它。
使用給定的代碼,那一定是問題。
但是問題不在於將類型轉換為char **的問題。
需要在您的代碼中設置幾項內容:
看一下下面的代碼:假設您使用malloc動態分配了一些內存,或者使用了一個指針來指向某個位置,如下所示。
#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 */
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.