We may often write such code:
Int add (int a, int B)
{
Return a + B;
}
Of course, this is a reasonable way to make the return value of the function be int. Therefore, an int type value will be returned after the function is called.
The question I want to discuss today is certainly not this. Please refer to the following code:
Char * Func_1 (void)
{
Char str [30] = "Bruce ";
Cout <"str:" <str <endl;
Return str ;//???????
}
Is there a problem here? Isn't it the same as above?
Of course, they are different. The above function returns a specific value, but this function returns an address. Can the function return an address? Of course you can, but not here.
The address here is the address of a local variable str. We all know that local variables are stored in the stack. When the function is executed, the local variables in the local variable will execute the stack operation. However, after the function is executed, the data in the stack pops up to free up the stack space.
Therefore, after the function is executed, the pointer points to an address, but the data it points to is no longer available.
Is that true?
The following is an example:
#include <iostream> #include <string> using namespace std; const char* testValue = "BruceZhang"; char gstr[30] = {0}; char* Func_1(void); char* Func_2(void); int main(void) { char* func_1; char* func_2; func_1 = Func_1(); func_2 = Func_2(); cout<<"func_1:"<<func_1<<endl; cout<<"func_2:"<<func_2<<endl; system("pause"); return 0; } char* Func_1(void) { char str[30] = "Bruce"; cout<<"str:"<<str<<endl; return str; } char* Func_2(void) { strcpy(gstr, testValue); cout<<"gstr:"<<gstr<<endl; return gstr; } #include <iostream>#include <string>using namespace std;const char* testValue = "BruceZhang";char gstr[30] = {0};char* Func_1(void);char* Func_2(void);int main(void){ char* func_1; char* func_2; func_1 = Func_1(); func_2 = Func_2(); cout<<"func_1:"<<func_1<<endl; cout<<"func_2:"<<func_2<<endl; system("pause"); return 0;}char* Func_1(void){ char str[30] = "Bruce"; cout<<"str:"<<str<<endl; return str;}char* Func_2(void){ strcpy(gstr, testValue); cout<<"gstr:"<<gstr<<endl; return gstr;}
The following is the result of running on my computer:
It can be seen that the "Bruce" should be displayed, and the unidentifiable garbled characters are displayed. Therefore, the above statement is verified.
Therefore, when writing a program, you must note that if the returned value is a value, you can perform bold operations. However, if the returned value is an address, then we need to consider whether it is a local automatic variable.