# Include <string> <br/> # include <iostream> <br/> using namespace STD; </P> <p> int main () <br/>{< br/> char str1 [] = "hello"; <br/> char * str2 = "hello "; <br/> char str3 [] = {'h', 'E', 'l', 'l', 'O '}; <br/> cout <sizeof (str1) <'/t' <strlen (str1) <Endl; <br/> cout <sizeof (str2) <'/t' <strlen (str2) <Endl; <br/> cout <sizeof (str3) <'/t' <strlen (str3) <Endl; <br/> system ("pause"); <br/> return 0; <br/>}< br/>
Display output:
6 5 // character array, "hello" stored on the stack
4 5 // "hello" is stored in the string Constant Area
5 19 // No '/0', so the length is not fixed
Compilation of char str1 []Code:
7: Char str1 [] = "hello"; <br/> 004117b8 mov eax, dword ptr [String "hello" (417870 h)] <br/> 004117bd mov dword ptr [ebp-10h], eax <br/> 004117c0 mov CX, word ptr ds: [417874 H] <br/> 004117c7 mov word PTR [ebp-0Ch], CX <br/> // get str1 address, consistent with the starting address of "hello" in the stack <br/> 004117d3 Lea ECx, [ebp-10h] <br/> 004117d6 push ECx <br/> 004117d7 call @ ILT + 600 (_ strlen) (41125dh)
We can see that "hello" also exists in the constant area, but is still copied to the stack, and str1 points to the stack.
The Assembly Code of char * str2:
004117ae mov dword ptr [str2], offset string "hello" (417870 h) <br/> ...... <Br/> 004117bd mov ECx, dword ptr [str2] <br/> 004117c0 push ECx <br/> 004117c1 call @ ILT + 600 (_ strlen) (41125dh)
The str2 pointer points directly to "hello" in the constant area"
The following code has an error during running:
# Include <string> <br/> # include <iostream> <br/> using namespace STD; </P> <p> int main () <br/>{< br/> char * str2 = "hello"; <br/> str2 [0] = 'G '; <br/> system ("pause"); <br/> return 0; <br/>}< br/>
Hello cannot be changed in the constant area