简体   繁体   中英

Problems with strcpy and strcat

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM