Char P [] and char * P

Source: Internet
Author: User
In the function, char P [] = "Hello World" and char * P = "Hello World" have different effects. Why? Please let us know!

Please refer to two Program :
(1)
Char * getstring (void)
{
Char P [] = "Hello World ";
Return P;
}
Void main ()
{
Char * STR = NULL;
STR = getstring ();
Cout <STR <Endl;
}

(2)
Char * getstring (void)
{
Char * P = "Hello World ";
Return P;
}
Void main ()
{
Char * STR = NULL;
STR = getstring ();
Cout <STR <Endl;
}

Why (1) Output garbled characters and (2) Output Hello World
I think it may be the difference between the pointer string and the array string when space is allocated. Does anyone know the specifics? Thank you!
//////////////////////////////////////// /////////////////////// I know this because I have been troubled by this problem and have made some discussions.
"Hello world" is actually stored in the data zone as a static string, but the Write Program does not know this address, and the program itself knows. When a function
{Char P [] = "Hello World ";...}
When using this static string, it is actually equivalent:
Char P [12];
Strcpy (P, "Hello World ");
....
P [12] is temporarily allocated in the stack. Although P points to "Hello World", it is a replica, not an original. When the function ends, char P [] is recycled by the program, so the content of P [] is no longer "Hello World.
If char * P = "Hello world" is used, P points to the location where the static string is stored, that is, to point to the original "Hello World", of course, no problem.

If you want to stick to Char P [] instead of char * P, the valid method must be:
{
Static char P [] = "Hello World ";
Return P;
}
The reason is clear to me. Static char [] is static and stored in the data zone.

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.