I am trying to implement Copystring functionality, wherein I don't want to return my destination string as a return value, and want to send it as out parameter in the below CopyString() method. I am also keen to have memory allocated within the CopyString block only.
#include "stdafx.h"
void CopyString (char *strSrc, char* strDsn, int iLen)
{
strDsn = new char[iLen];
for (int i=0; i< iLen; i++)
strDsn[i] = strSrc[i];
}
int main()
{
char * mystrSrc = "Testing Copy Method";
int iLen = 0;
for(int i=0; mystrSrc[i] != '\0'; i++)
iLen++;
char * mystrDsn = 0;
CopyString (mystrSrc, mystrDsn, iLen);
printf(mystrDsn);
return 0;
}
Now as I am doing Pass-by-Value, strDsn object of CopyString method will get destroy when Stackunwinding takes place, and hence caller will fail to get the copied value. How to go ahead?
char*& strDsnstrDsn = new char[iLen];won't work as you expect, unless you take this parameter by reference:void CopyString (char* strSrc, char*& strDsn, int iLen)char* strDsn&is not right.const char *mystrSrc = "..."). The source pointer toCopyStringshould be const (const char *strSrc). The memory allocated inCopyStringwill need to be released after the printf (delete[] mystrDsn). Passing a non-format string as the format to printf can be dangerous as it will be parsed. (printf("%s",mystrDsn)).