为什么main()参数argv类型为char * []而不是const char * []? [英] Why is main() argument argv of type char*[] rather than const char*[]?

查看:80
本文介绍了为什么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.

这篇关于为什么main()参数argv类型为char * []而不是const char * []?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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