0

I just learned about the cstring and some functions in cstring library. When I tried to use the function strcpy, I got a confusing problem. Can anyone thoroughly explain to me why the first code doesn't work while the second one runs totally fine?

First code:

  char *str1 = "hello";
  char *str2 = "hi";
  strcpy(str1, str2);
  cout << str1;

Second code

   char str1[] = "hello";
   char *str2 = "hi";
   strcpy(s1,s2);
   cout << str1;

I guess the problem is how I declare the variable str1 but I still have no idea why it doesn't work when str1 is a pointer.

kutycoi123
  • 13
  • 2
  • 1
    C++11 doesn't permit either because you're storing a string literal in a non-const `char*`. It's likely your compiler would warn/error if you turn those up. – chris Apr 13 '17 at 18:30
  • 1
    Use `std::string` so you don't have to worry about it. Also `char *str1 = "hello";` should be a compiler error/warning. If you are not getting one you need to turn up the settings. – NathanOliver Apr 13 '17 at 18:30
  • I think [this](http://stackoverflow.com/a/1704433/4926171) will answer your query. – AntGeorge Apr 13 '17 at 19:55

1 Answers1

0

First, statement char *str1 = "hello" should give you a warning because you are assigning a pointer to string literal "hello" (which is const) to non-const pointer char* str1. But if you wrote const char *str1 = "hello", then the warning would disappear but you'd get an error with strcpy, because the first operand must not be const.

The second statement works because in char str1[] = "hello", variable str1 is actually an array (not a pointer), which is initialised with a let's say copy of "hello". Hence, you are allowed to overwrite the contents of str1 later on. Note that str1 is not a pointer but an array; it rather decays to a pointer (to the memory of the first character of the array) when used in the context where a pointer is expected.

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58