The difference between a string pointer (char*) and a character array (char [])

Source: Internet
Author: User

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 [])

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.