When I wrote the following code and executed it, the compiler said
deprecated conversion from string constant to
char*
int main()
{
char *p;
p=new char[5];
p="how are you";
cout<< p;
return 0;
}
It means that I should have written const char *
.
But when we pass arguments into main
using char* argv[]
we don't write const char* argv[]
.
Why?
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 doingp[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 acceptconst char*
as parameters, but do indeed requirechar*
, therefore you can't use a string constant to invokemain
.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.Input:
Output:
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:
is always illegal, because you are not allowed to mess with string literals like that, so the pointer should be to a const char.