Why is main() argument argv of type char*[] rather than const char*[]?

与世无争的帅哥 提交于 2019-12-03 04:32:22

Because ... argv[] isn't const. And it certainly isn't a (static) string literal since it's being created at runtime.

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;
}

Input:

g++ -o test test.cc

./test hoo

Output:

foo

This is not a comment on why you'd want to change argv, but it certainly is possible.

Historical reasons. Changing the signature of main() would break too much existing code. And it is possible that some implementations allow you to change the parameters to main from your code. However code like this:

char * p = "helllo";
* p = 'x';

is always illegal, because you are not allowed to mess with string literals like that, so the pointer should be to a const char.

why is it required for char* to be constant while assigning it to a string

Because such literal strings (like "hi", "hello what's going on", etc), are stored in the read-only segment of your exe. As such, the pointers that point to them need to point to constant characters (eg, can't change them).

You are assigning a string constant (const char*) to a pointer to a non-constant string (char *p). This would allow you to modify the string constant, e.g. by doing p[0] = 'n'.

Anyway, why don't you use std::string instead ? (you seem to be using C++).

If you look at execution functions like execve, you will see that they actually don't accept const char* as parameters, but do indeed require char*, therefore you can't use a string constant to invoke main.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!