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
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.