为什么我可以为字符串字面量分配一个char *指针 [英] why can I assign a string literals to a char* pointer

查看:347
本文介绍了为什么我可以为字符串字面量分配一个char *指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为 c ++ 中的字符串文字是 const char * 的类型。并且不能将 const char * 对象分配给非常量char * 对象。但在Visual studio 2010.下面的代码可以编译没有错误或警告,这将产生一个运行时错误。

I think the string literals in c++ is the type of const char*. And you can't assign const char* object to a non-constant char* object. But in Visual studio 2010. The following code can compile without errors or warnings, which will however yield a runtime error.

int main(void)
{      
    char *str2 = "this is good";
    str2[0] = 'T';
    cout << str2;
    getchar();
    return 0;
}

如果我们不修改字符串的值, is ok:

And if we don't modify the value of the string, reading the value is ok:

for(char *cp = str2; *cp !=0; ++cp) {
    printf("char is %c\n", *cp);
}
getch();
return 0;

那么为什么我们可以在这里为char *赋值一个const char * >

So why can we assign a const char* to a char* here?

推荐答案

问题是在VC ++下,但在GCC中有一个有意义的警告:

The question is under VC++, but in GCC it has a meaningful warning:


警告:不推荐从字符串常量转换为char *
[-Wwrite-strings]

warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

这个警告意味着编译器将应用隐式转换,尽管const /非const差异。所以,这段代码是OK的(在运行时没有任何修改):

This warning implies that compiler will apply an implicit conversion despite const/non-const differences. So, this code is OK (without any modification in run-time):

char *str2 = "this is good";

但是修改 str2 会产生未定义的行为。

However modifying str2 yields an undefined behavior.

这篇关于为什么我可以为字符串字面量分配一个char *指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆