Talk about char *num= "123"; and char num[4]= "123"; the difference

Source: Internet
Author: User

Recently wrote a program to find such a problem

#include <iostream>#include<string.h>using namespacestd;voidReverseChar*str) {    intlen=strlen (str); Char*p=str; Char*q=str+len-1;  while(p<q) {Chartemp=*p; *p=*Q; *q=temp; P++; Q--; }}intMain () {Char*n1="123"; Charn2[4]="456";    Reverse (N1);    Reverse (N2); return 0;}

Execute reverse (N1), when the following error occurs, and if the sentence is commented out reverse (N2), but can run smoothly

The main problem now is to initialize a character array and initialize a pointer to a string, the former can change the individual contents of the string by the pointer, but the latter can not, do not understand, so consult the books,

The answer is found in the chapter "C Primer Plus version Fifth" on strings.

The following procedure is further simplified to observe the focus:

1, only in the program to write the following two sentences program, the program runs smoothly

    Char n1[4]="123";    n1[0]='1';

2, only in the program to write the following two sentences program, the program run error, error and the same as above

    Char *n2="123";    n2[0]='1';

Why did it go wrong? The explanation in the book is that the compiler may select the same single copy in memory to represent all the same string literals, and if some of the characters of the string are allowed to be changed by a pointer, there will be errors in referencing strings elsewhere.

The advice given in the book is to use the const modifier when initializing a string pointer, so that you can avoid finding errors when you use them, and of course just turning the run error into a compilation error.

Talk about char *num= "123"; and char num[4]= "123"; the difference

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.