for cstr, it work exactly as what I expected, but for cstrp, no matter what I input, with a null terminator or not, I just got nothing printed. why? can we really use cstrp in that way or not? How to use it? Thanks!
Your problem is that cstrp isn't pointing to any memory area that can receive the characters -- i.e., it's uninitialized. This is in contrast with the cstr area, which points to an area of memory that can hold 5 characters.
To use cstrp, you first need to initialize it. For example:
char *cstrp = new char[5];
Then you can do what you're doing.
Don't forget to delete the memory when you're done:
this code will only output the first three characters of s2, why? so a string is not the one you can put anything in it?! you got be careful there is no \0? why it is designed like that?
char *cstrp=cstr;//works the same as char *cstrp=new char[5];
No it doesn't. char *cstrp=newchar[5]; allocates some new memory on the heap, and sets cstrp to be the address of that new memory.
char *cstrp=cstr; just sets cstrp to be the address of the first element of cstr.
Very different things!
you got be careful there is no \0? why it is designed like that?
Because a std::string uses a C-style character array to store the actual characters of that string. It uses the '\0' in the same way as you would if you were directly using a C string.