const char* 指针算术警告
使用我的编译器(Apple llvm-gg-4.2),此代码:
void fun1(const char *s)
{
char* t = s+1;
}
void fun2(char *s)
{
char* t = s+1;
}
int main(void)
{
char* a;
fun1(a);
fun2(a);
}
给出此警告:
junk.c:3:警告:初始化丢弃 fun1 上指针目标类型的限定符
,但不在 fun2 上。为什么?
With my compiler (Apple llvm-gg-4.2) this code:
void fun1(const char *s)
{
char* t = s+1;
}
void fun2(char *s)
{
char* t = s+1;
}
int main(void)
{
char* a;
fun1(a);
fun2(a);
}
gives this warning:
junk.c:3: warning: initialization discards qualifiers from pointer target type
on fun1 but not on fun2. Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
fun1 正在使用 const char* 并被分配给 char*
而 fun2 接受一个 char* 并分配给 char* ,这很好。
如果您将常量指针分配给非常量指针,这意味着您可以使用常量指针修改常量指针
在这种情况下,如果您执行
t[0],则在 fun1 内部= 'a'
它不合法,因为您正在修改 const 内存,这就是编译器警告您的原因fun1 is taking const char* and is being assigned to char*
Whereas fun2 is taking a char* and being assigned to char* which is fine.
If you are assigning a constant pointer to a non-const pointer, this means you can modify the const pointer by using the const pointer
In this case, inside fun1 if you do
t[0] = 'a'
its not legal because you are modifying const memory, which is why compiler warns you在
fun1
中,s
是一个const char *
。当您执行char* t = s+1;
时,您就从s
中“删除”了该const
状态。因此,“放弃限定符”。如果这是 C++,您将收到编译器错误而不是警告。In
fun1
,s
is aconst char *
. When you dochar* t = s+1;
, you "remove" thatconst
status froms
. Hence the "discards qualifiers". If this were C++, you would get a compiler error instead of a warning.原因是在
fun1
中,您将const char *
转换为char *
。这会丢失 const 限定符,并为修改函数可能不打算修改的数据打开了大门。要解决此问题,请将
fun1
主体更改为The reason why is in
fun1
you are convertingconst char *
to achar *
. This is losing theconst
qualifier and opening the door to modify data the function likely didn't intend to be modified.To fix this change the
fun1
body to