Differences string literal is assigned to declaration defines an array of pointers

String literal is assigned to declaration defines the difference between pointers and arrays

A string things to the amount can not be modified, which is iron reason! So the question is? why

char *p="abc";

*p='d';//(wrong!)

char p2[]="abc";

p2[0]='d';//(right!)

This is for the hair? For the hair ah? Not to say it can not be modified constant good? char * p = "abc" is a constant? No const ah! Why p2 [0] = 'd' correctly, * p = 'd' wrong?

Listen I could go on, you first need to know a little, "abc" belong string literal (string constant), "string literal can not be modified" is stored in the constant storage area, can not be modified.

①char * p = "abc" pointer variable p to point to the string "abc" in the first character, i.e., p is equal to "abc" string 'a' address, where * p = 'd', i.e. To address p value stored from the original 'a' modify 'd', so "abc" will become a "DBC", since the "literal character string can not be modified", so the compiler determines * p = 'd 'is wrong.

 

② the char p2 [] = "abc" string variable declaration because its length may be omitted, in which case the compiler will automatically calculate the length, the compiler will allocate space p2 4 characters, which is enough to store " abc "characters and a null character. Look up! The compiler will allocate space for the four-character p2! , This time produced two address blocks (Ci speak their made), a block address is stored in a string literal "abc" consecutive addresses (in the constant storage area), the other is assigned the compiler is p2 4-character space (stack area). Next, represented by FIG.

As shown, char p2 [] = "abc" is the value passed through a process similar to that of the 'a', 'b', 'c', '\ 0' four characters will be passed to the compiler in the stack area 4 characters assigned to p2 consecutive address space, due to the stack area thus read-write data, i.e., may be modified, p2 [0] = 'd'; i.e., the compiler allows the stack area 'a' modified 'd' .

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/qq_29250265/article/details/94546172