Differences between a C pointer string and an array string

Source: Internet
Author: User
  1. In ansi c, the String constant created during pointer Initialization is defined as read-only. If you try to modify the value of this string through a pointer, the program will be undefined. In some compilers, A String constant is stored in a text segment that can only be read to prevent modification.
  2. Arrays can also be initialized using string constants:

Char A [] = "abcdefg ";

If the pointer is the opposite, the array initialized by the String constant can be modified. A single character can be changed later.

As follows:

(1) modify the data in the pointer string

# Include <string. h> # include <stdio. h> int main () {char * Buf = "abcdefg"; printf ("Buf = % C \ n", Buf [2]); buf [2] = 'M'; printf ("end! \ N ");}

The compilation is successful, but an error occurs during the program running:

(2) modify the data in the array string

# Include <string. h> # include <stdio. h> int main () {char Buf [] = "abcdefg"; printf ("Buf = % C \ n", Buf [2]); buf [2] = 'M'; printf ("Buf = % s \ n", Buf); printf ("end! \ N ");}

You can see that the program runs normally:

(-------- End --------)

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.