Although no error will be reported by doing this, trying to modify the string 123 pointed to by p will cause a memory access violation. Because "123" is a string constant, stored in a read-only storage area. The reason why const char* is required is to prevent programmers from mistakenly modifying 123.
Answers for Beginners "123" is an object of const char type. const char * p should be read from right to left, which means that p is a pointer and the object pointed to is of type const char. This is not correct. What? In the same way, you are right to add p = "456"; at the end, as long as the object pointed to by p is const char.
char *p = "123"; It is actually two processes. Allocate string space in the constant area, declare the character pointer p, and p points to the memory space where the string is located. If there is anything wrong, please correct me immediately
Although no error will be reported by doing this, trying to modify the string
123
pointed to by p will cause a memory access violation. Because "123" is a string constant, stored in a read-only storage area. The reason whyconst char*
is required is to prevent programmers from mistakenly modifying123
.Answers for Beginners
"123" is an object of const char type. const char * p should be read from right to left, which means that p is a pointer and the object pointed to is of type const char. This is not correct. What? In the same way, you are right to add p = "456"; at the end, as long as the object pointed to by p is const char.
Does
char *p = "123";
represent a character array? That is stringYou will see a warning after compiling and adding
-Wall
.char *p = "123"; It is actually two processes. Allocate string space in the constant area, declare the character pointer p, and p points to the memory space where the string is located. If there is anything wrong, please correct me immediately
The pitfalls left by C language
This is left for compatibility with c