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

前端 未结 9 1751
耶瑟儿~
耶瑟儿~ 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 10:01

    You mistake two things: making pointer point to something different (this is what assignment does) and copying some data to a place pointed by pointer.

    at = "tw";
    

    this code makes at point to a literal "tw" created somewhere in read-only memory. Trying to write to it is an undefined behaviour.

    char *at = new char [3];
    strcpy(at,"t");
    

    this code allocates memory for three chars and makes at point to this part of memory (line 1) and then copies some data to memory pointed by at.

    And remember, that memory allocated with new[] should be deallocated with delete[], not delete

    I advice you to learn more about pointers. This discussion covers this.

提交回复
热议问题