Recently wrote a program to find such a problem
#include <iostream>#include<string.h>using namespacestd;voidReverseChar*str) { intlen=strlen (str); Char*p=str; Char*q=str+len-1; while(p<q) {Chartemp=*p; *p=*Q; *q=temp; P++; Q--; }}intMain () {Char*n1="123"; Charn2[4]="456"; Reverse (N1); Reverse (N2); return 0;}
Execute reverse (N1), when the following error occurs, and if the sentence is commented out reverse (N2), but can run smoothly
The main problem now is to initialize a character array and initialize a pointer to a string, the former can change the individual contents of the string by the pointer, but the latter can not, do not understand, so consult the books,
The answer is found in the chapter "C Primer Plus version Fifth" on strings.
The following procedure is further simplified to observe the focus:
1, only in the program to write the following two sentences program, the program runs smoothly
Char n1[4]="123"; n1[0]='1';
2, only in the program to write the following two sentences program, the program run error, error and the same as above
Char *n2="123"; n2[0]='1';
Why did it go wrong? The explanation in the book is that the compiler may select the same single copy in memory to represent all the same string literals, and if some of the characters of the string are allowed to be changed by a pointer, there will be errors in referencing strings elsewhere.
The advice given in the book is to use the const modifier when initializing a string pointer, so that you can avoid finding errors when you use them, and of course just turning the run error into a compilation error.
Talk about char *num= "123"; and char num[4]= "123"; the difference