e******d 发帖数: 310 | 1 //why the following assignment is allowed? I think we need use
// const char* str = "this is a test. \n" ; instead.
// then we can prevent assignment like
// str[1] = 'g';
// thanks
char* str = "this is a test. \n";
str[1] = 'g';
|
t*****g 发帖数: 1275 | 2 c doesn't prohibit you from doing str = 0 and str[1] = 'g' either.
【在 e******d 的大作中提到】 : //why the following assignment is allowed? I think we need use : // const char* str = "this is a test. \n" ; instead. : // then we can prevent assignment like : // str[1] = 'g'; : // thanks : char* str = "this is a test. \n"; : str[1] = 'g'; :
|
s*******e 发帖数: 27 | 3 It causes runtime exception (access violation) if you run the following code.
Complier is not able to detect such error since it is very difficult to do
such deduction without const pointer. It could theretically detect it but
require much more work to cover all the cases or all the pointer
manipulations, I think.
char* str = "this is a test. \n";
str[1] = 'g';
【在 e******d 的大作中提到】 : //why the following assignment is allowed? I think we need use : // const char* str = "this is a test. \n" ; instead. : // then we can prevent assignment like : // str[1] = 'g'; : // thanks : char* str = "this is a test. \n"; : str[1] = 'g'; :
|
X****r 发帖数: 3557 | 4 字符串常量类型为char*而不是const char*是C语言的历史遗留问题。
你自己程序里把字符串常量类型当const char*看待就好了。
【在 e******d 的大作中提到】 : //why the following assignment is allowed? I think we need use : // const char* str = "this is a test. \n" ; instead. : // then we can prevent assignment like : // str[1] = 'g'; : // thanks : char* str = "this is a test. \n"; : str[1] = 'g'; :
|
D****A 发帖数: 360 | 5 由于系统的约束,语言的实现往往会很messy。
一般C compiler都默认string是存在只读段里的,所以运行时写入是禁止的。但
compiler分不清字符串还是数组,所以没加const就不会有编译错误。如果string放在
可写段里,就不会出错。
【在 e******d 的大作中提到】 : //why the following assignment is allowed? I think we need use : // const char* str = "this is a test. \n" ; instead. : // then we can prevent assignment like : // str[1] = 'g'; : // thanks : char* str = "this is a test. \n"; : str[1] = 'g'; :
|