为什么此C ++代码不会对const发生错误

父亲
char* s1 = new char[30];
char s2[] = "is not";
const char* s3 = "likes";
s3 = "allows";
strcpy( s2, s3 );
sprintf( s1, "%s %s %s using functions.", "C++", s2, "fast code" );
printf( "String was : %s\n", s1 );
delete[] s1;

我很困惑

const char* s3 = "likes";
s3 = "allows";

因为我认为s3是const,所以它不能更改。但是,当s3 = "allows"它起作用时。为什么?

songyuanyao

我认为s3是一个常量

不,s3不是const本身,它是const的指针,所以s3 = "allows";很好,并且*s3 = 'n';会失败。

如果您的意思是const指针,char* const s3并且const char* const s3都是const指针,s3 = "allows";则将失败。

摘要(注意的位置const

char* s3是指向非常量的非常量指针,两者s3 = "allows";*s3 = 'n';都很好。
const char* s3是指向const的非const指针,s3 = "allows";很好并且*s3 = 'n';失败。
char* const s3是指向非const的const指针,s3 = "allows";失败并且*s3 = 'n';可以。
const char* const s3是常量指针为const,都s3 = "allows";*s3 = 'n';会失败。

请参见指针的常数

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章