为什么这不是安全投下'字符**``来为const char **`? [英] Why it's not safe to cast `char **` to `const char **`?
本文介绍了为什么这不是安全投下'字符**``来为const char **`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
编译这个程序:
的#include<&stdio.h中GT;无效的主要(){
字符* S =直升机;
焦炭** SP =&放大器; S;
为const char ** CSP = SP;
为const char * CS = * CSP;
的printf(%S \\ n,CS);
}
得到警告:
cc.c:在函数'主':
cc.c:6:24:警告:初始化从兼容的指针类型[默认启用]
为const char ** CSP = SP;
解决方案
的char ** SP
SP是一个指向字符指针和SP,SP *,**和SP都
可变
块引用>
为const char ** CSP
CSP是一个指针的指针为const char和,CSP和CSP *是
可变的,但** CSP是常量
块引用>现在让我们看看为什么
为const char ** CSP = SP
不是安全的。为const char Imconst ='A';
字符*不变;
为const char ** ImConstPtr =安培;一成不变的; //这是非法的,但如果它是允许的
* ImConstPtr =安培; Imconst;
*不变='1'; //我们正试图将分配给Imconst希望这清除了疑问。
Compile this program:
#include <stdio.h> void main() { char *s = "helo"; char **sp = &s; const char **csp = sp; const char *cs = *csp; printf("%s\n", cs); }
get the warning:
cc.c: In function ‘main’: cc.c:6:24: warning: initialization from incompatible pointer type [enabled by default] const char **csp = sp;
解决方案
char **sp
sp is a pointer to pointer to char and sp, *sp, and **sp are all mutable
const char **csp
csp is a pointer to pointer to const char and, csp and *csp are mutable but **csp is const
Now lets see why
const char** csp = sp
is not safe.const char Imconst = 'A'; char* ImMutable; const char** ImConstPtr = &ImMutable; // This is illegal but if it is allowed *ImConstPtr = &Imconst; *ImMutable = '1'; // We are trying to assign to "Imconst"
Hope this clears the doubt.
这篇关于为什么这不是安全投下'字符**``来为const char **`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文