String pointer and character array

Source: Internet
Author: User

One person in the group asked a question

Int main () {char * P = "world"; P [0] = '2'; printf ("% s", P );}

Why?
After debugging and running, the system reports an error.

This is a good summary on the Internet.

(1) char * s = "hello"; // "hello" is a String constant, S is a pointer to a constant, and constants cannot be changed, it cannot be written as s [0] = X, but the pointer value can be changed to point to different constants, such as S = "Xeon ";

(2) Char s [] = "hello"; // pointer constant. The value of s cannot be modified, but the content pointed to by s can be modified. s [0] = x
The difference between the two is:
(1) The defined string is inProgramCannot be modified because it is stored inCodeSegment;
(2) The defined string can be modified and stored in the data segment or stack.

The two string-defining methods are slightly different inside and outside the function.

* Function External:
(1) char * s = "hello";/* defines the pointer S (Data Segment) and constant string "hello" (Data Segment). The value of S is the first address of the string */
(2) Char s [] = "hello";/* defines the character array S, and the array content is "hello" (code segment ), note that S is only a symbol, not a variable entity */

* Internal function:
If (1) and (2) are used internally in the function, the "hello" string is stored in the code segment. When the function is called,
(1) only assign the first address of the string "hello" to S
(2) copy the string "hello" to the stack and assign the first address of the copy string to S.

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.