Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 276
Frustrated Coder Avatar asked Jan 30 '23 05:01

Frustrated Coder


1 Answers

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.

like image 200
Brian Roach Avatar answered Feb 08 '23 15:02

Brian Roach