简体   繁体   English

const char* 指针算术警告

[英]const char* pointer arithmetic warning

With my compiler (Apple llvm-gg-4.2) this code:使用我的编译器(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);
}

gives this warning:给出这个警告:

junk.c:3: warning: initialization discards qualifiers from pointer target type junk.c:3:警告:初始化丢弃来自指针目标类型的限定符

on fun1 but not on fun2.在 fun1 上,但不在 fun2 上。 Why?为什么?

fun1 is taking const char* and is being assigned to char* fun1 正在使用 const char* 并被分配给 char*
Whereas fun2 is taking a char* and being assigned to char* which is fine.而 fun2 正在使用 char* 并被分配给 char* ,这很好。

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 中执行t[0] = 'a'它是不合法的,因为你正在修改 const memory,这就是编译器警告你的原因

In fun1 , s is a const char * .fun1中, s是一个const char * When you do char* t = s+1;当你做char* t = s+1; , you "remove" that const status from s . ,您从s中“删除”该const状态。 Hence the "discards qualifiers".因此,“丢弃限定符”。 If this were C++, you would get a compiler error instead of a warning.如果这是 C++,您将收到编译器错误而不是警告。

The reason why is in fun1 you are converting const char * to a char * .fun1中,您将const char *转换为char *的原因。 This is losing the const qualifier and opening the door to modify data the function likely didn't intend to be modified.这将丢失const限定符,并为修改 function 可能不打算修改的数据打开了大门。

To fix this change the fun1 body to要解决此问题,请将fun1主体更改为

const char* t = s+1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM