How does the C ++ pointer Parameter Pass the memory ?, Pointer Transmission
Several examples are provided to illustrate the memory transfer problem of the C ++ pointer parameter.
Example 1:
Void GetMemory (char * p, int num)
{
P = (char *) malloc (sizeof (char) * num );
Return;
}
Int main (void)
{
Char * str = NULL;
GetMemory (str, 30 );
Std: cout <str <std: endl; // str is still NULL
}
Analysis: If the function parameter is a pointer, do not expect this pointer to apply for dynamic memory. In example 1, the main function calls GetMemoty (str, 30) and does not enable str to obtain the expected memory. str is still NULL. In the GetMemory function, the compiler always creates a temporary copy for each parameter of the function. The copy of the pointer parameter p is _ p, and the compiler makes _ p = p. If the program in the function modifies the content of _ p, the content of parameter p is modified accordingly. This is why pointers can be used as output parameters. In example 1, _ p applied for a new memory, but changed the address of the memory indicated by _ p, but p was not changed at all. Therefore, the GetMemory function cannot output anything. In fact, each execution of GetMemory will leak a piece of memory because the memory is not free to be released. If you need to use the pointer parameter to request memory, you should use "pointer to Pointer" instead. For details, see Example 2.
Example 2:
Void GetMemory_2 (char ** p, int num)
{
* P = (char *) malloc (sizeof (char) * num );
Return;
}
Int main (void)
{
Char * str = NULL;
GetMemory (& str, 30 );
Strcpy (str, "hello world ");
Std: cout <str <std: endl;
Free (str );
}
Analysis: the temporary copy of * p in the GetMemory_2 function parameter is _ * p. In the function, a new memory is applied, which is equivalent to changing the content of pointer _ * p, thus, the content of * p is changed, so the memory application is successful.