잡담

call by reference

tomato13 2014. 5. 10. 11:56

Let's see an example below.

 

main()
{                  
     char* pPtr;

     MyStringCopy(pPtr, "hello");

}

 

MyStringCopy(char* dest, char* src)
{
     dest = new char[sizeof(src)];
     strcpy(dest, src);
}

 

The upper program returns wrong answer becuase the main function's pPtr has not assigned no memory space and indicates wrong position.
You should know that MyStringCopy's dest value is just copy value from main's pPtr.

The upper code is mapped with the attached left picture.

To resolve that problem, you can approach like below.

 

main()
{
     char* pPtr;

     MyStringCopy(&pPtr, "hello");

}

 

MyStringCopy(char** dest, char* src)
{
     *dest = new char[sizeof(src)];
     strcpy(dest, src);
}

 

In the upper case, you deliver the pPtr's address value. And MyStringCopy's dest value is copy of the pPtr pointer's address value( not pointer value). That means both funcions indicate same pPtr value. ( in other words, both functions know pPtr's value position. )

The upper code is mapped with the attached right picture.