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

前端 未结 9 1779
耶瑟儿~
耶瑟儿~ 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:50

    When you do

    char *at = ...;
    
    at = "hello";
    

    You're basically overwriting the pointer value (i.e., the address of the memory allocated for you by new[]) with the address of a static constant string. This means that when you later delete that memory, you're passing delete a pointer not previously returned by new.

    That is a bad thing to be doing.

    In C and C++, assignments to pointers typically don't do anything to the memory being pointed at, they change the pointer itself. This might be confusing if you're used to a language where strings are more of "first class citizens".

    Also, you should use delete[] if you used new[].

提交回复
热议问题