由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
Programming版 - A question about cost char*
相关主题
C 语言,初学者,简单问题(2)c++ template specialization 参数
数组指针的问题请教一个关于字符指针的简单问题
问个字符串的基本问题a string define question (c++)
四道C++面试题这个C++程序为什么不能运行
在c中如果一个function return 一个字符串问一个 char * 和 char [] 的问题
问个c语言的问题C ++ 问题
c字符串内存分配问题code question
这个在c++ const不变,不能用相同地址的变量改,咋做的嵌入式编程问题
相关话题的讨论汇总
话题: str话题: char话题: assignment话题: test话题: const
进入Programming版参与讨论
1 (共1页)
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';
:

1 (共1页)
进入Programming版参与讨论
相关主题
嵌入式编程问题在c中如果一个function return 一个字符串
一个const_cast问题问个c语言的问题
string operator +c字符串内存分配问题
一个C++ 的问题这个在c++ const不变,不能用相同地址的变量改,咋做的
C 语言,初学者,简单问题(2)c++ template specialization 参数
数组指针的问题请教一个关于字符指针的简单问题
问个字符串的基本问题a string define question (c++)
四道C++面试题这个C++程序为什么不能运行
相关话题的讨论汇总
话题: str话题: char话题: assignment话题: test话题: const