为什么main()参数argv类型为char * []而不是const char * []?
当我编写并执行以下代码时,编译器说
When I wrote the following code and executed it, the compiler said
不建议从字符串常量转换为
char*
int main()
{
char *p;
p=new char[5];
p="how are you";
cout<< p;
return 0;
}
这意味着我应该写const char *
.
但是,当我们使用char* argv[]
将参数传递给main
时,我们不要编写const char* argv[]
.
But when we pass arguments into main
using char* argv[]
we don't write const char* argv[]
.
为什么?
因为... argv[]
不是const.而且它肯定不是(静态)字符串文字,因为它是在运行时创建的.
Because ... argv[]
isn't const. And it certainly isn't a (static) string literal since it's being created at runtime.
您要声明一个char *
指针,然后为其分配一个字符串文字,根据定义,该文字是常量;实际数据位于只读存储器中.
You're declaring a char *
pointer then assigning a string literal to it, which is by definition constant; the actual data is in read-only memory.
int main(int argc, char **argv) {
// Yes, I know I'm not checking anything - just a demo
argv[1][0] = 'f';
std::cout << argv[1] << std::endl;
}
输入:
g ++ -o测试test.cc
g++ -o test test.cc
./test hoo
./test hoo
输出:
foo
foo
这不是您要更改argv
的为什么的评论,但肯定有可能.
This is not a comment on why you'd want to change argv
, but it certainly is possible.