Why must a pointer to a char array need strcpy to assign characters to its array and double quotes assignment will not work?

前端 未结 9 1754
耶瑟儿~
耶瑟儿~ 2021-02-14 09:23

The first example does not work when you go to delete the pointer. The program either hangs when I add the null terminator or without it I get:

Debug Assertion Fai

9条回答
  •  孤城傲影
    2021-02-14 09:48

    In your first example you are allocating some memory and pointing to it with the "at" variable. When you do

    at = "tw"
    

    you are effectively re-pointing the char * to a constant character string. This causes you to leak memory. When you go on to delete "at" you are attempting to delete stack memory.

    strcpy goes through each character and copies their values to the new memory you allocate. This is also known as a deep copy.

提交回复
热议问题