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.