Original: http://www.blogbus.com/kavine-logs/29243638.html
Today in the writing of a few small functions, half-day adjustment, long-term non-use of C + + knowledge is almost forgotten, hurriedly pick up to deal with the upcoming candidates.
void Main ()
{
char* pStr1 = "hello!";
Char pstr2[] = "hello!";
Change (PSTR1);
Change (PSTR2);
}
void Change (char* pinstr)
{
pinstr[0]= ' O ';
}
Both of the change compilations can pass, but the second one is found to be able to correctly modify the first letter as ' O ', while the first one fails to cause the program to die.
The basic knowledge is too poor, wood method, check the data, two methods to define the string is different.
The string pointer variable itself is a variable that holds the first address of the string. The string itself is stored in a contiguous memory space, headed by the first address, and ends with ' s ' as a string. Character arrays are composed of a number of array elements that can be used to hold the entire string.
The first method defines a single character in a string that can only be read and cannot be modified, such as cout<<pstr1[0]<<endl; But cannot do pstr1[0]= ' O '; Because it is considered a string constant, constants cannot be modified.
The second facet defines a string that has no such limit.
The difference between a string pointer (char*) and a character array (char [])