Transferred from: jianchi88http: // blog.csdn.net/jianchi88/article/details/6876405
#include<stdio.h>int main(){ char a[] = "hello world1"; char *p = "hello world2"; *(a+1)=‘q‘; *(p+1)=‘q‘; printf("%s\n",a); printf("%s\n",p);}
Running result
Segment error.
Note * (p + 1) = 'q ';
Running result
Hqllo world1
Hello World2
Cause:
I. A and P are different types: P is the pointer to the string, and a is the array that saves the string.
Char A [] = "Hello world1"; is an array of characters with initial values.
Char * P = "Hello World2"; Is a String constant pointer;
Pointer Variable P in the stack
String constant "Hello World2" in the global data zone, data segment, read-only, not writable
2. The "Hello World2" and "hello world1" strings are stored in different locations. "Hello world1" is saved on the stack
* (A + 1) = 'q' can be used for modification. "Hello World2" is saved in global data.
The location is in. rodata and cannot be modified * (p + 1) = 'Q'
3. In the case of only 2, the array name cannot be equivalent to an array pointer.
:
& P indicates the address of the pointer variable, not the first address of the string "Hello World2". P indicates the first address of the string. & A obtains
Is the first address of the string "hello.
Differences between siziof:
The following assumes that the memory space for saving variables is different when running on the ia32 platform.
Sizeof (p); // return 4, pointer size
Sizeof (a); // return 13, array size
5 char a [] = "Hello world1"; (GDB) p a $1 = "\ 000 <\ 006 ?? \ 005 ???? "// Empty (GDB) S 6 char * P =" Hello World2 "; (GDB) p a $2 =" Hello world1 "(GDB) P & A $3 = (char (*) [13]) 0xbfde0583 // stack (GDB) S 7 * (a + 1) = 'q'; (GDB) p $4 = 0x80484c0 "Hello World2" // in the Data Segment (GDB) P & P $5 = (char **) 0xbfde0590 // on the stack
Bytes --------------------------------------------------------------------------------------------
Interview question knowledge points:
When pointers are assigned to the same constant string, they actually point to the same memory address, but the constant memory initialization array is indeed different.
Char str1 [] = "Hello World"; char str2 [] = "Hello World"; string * str3 = "Hello World"; string * str4 = "Hello World "; q: Is str1 = str2 true? Is str3 = str4 true? (Note: the previous one is not valid, and the last one is valid)
Char A [] = "Hello World"; char B [] = "Hello World"; char * str1 = "Hello World"; char * str2 = "Hello World "; the first two are different, and the last two are the same, that is,! = B; str1 = str2;
Char A [] = "Hello world1" and char * P = "Hello World2)