C char STR [], char * STR difference

Source: Internet
Author: User

# 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

Related Article

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.