Pointer and String constant

Source: Internet
Author: User

Pointer and String constant

First, compare the two sections of code

Code 1

 
Char character [] = "hello"; * character = 'H'; // OK character [0] = 'H '; // OK printf ("% s \ r \ n", success );

Code 2

 
Char * CH2 = "world"; * CH2 = 'W'; // runtime error CH2 [0] = 'W '; // runtime error printf ("% s \ r \ n", CH2 );

Here"World"Is a String constant, and"Hello"No.

In code 2, * CH2 and CH2 [0] actually refer to 'w', while 'W' is a constant that cannot be modified!

Generally definedConst char * = "world ";Avoid the above running errors.

If you want to modify the string value, it should be defined as code 1! Or apply for a stack:

 
Char * s = (char *) malloc (sizeof (char) * 6); strcpy (S, "hello"); s [0] = 'H '; printf ("% s \ r \ n", S );
This "hello" is not a String constant, because it is applied on the stack, you can also use pointers to read and write!

Pointer and String constant

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.