Avinash Goud N J
Avinash Goud N J

Reputation: 89

Implementing CopyString functionality in C++

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?

Upvotes: 0

Views: 258

Answers (1)

scaryrawr
scaryrawr

Reputation: 867

I just copied your code and made a couple changes, but you need a pointer to a pointer if you want to get the newly created memory out (you can do a reference to a pointer, but eh, pointers show more on the calling side that it may be modified).

#include "stdafx.h"
void CopyString (char *strSrc, char** strDsn, int iLen) // strDsn is a ptr to ptr.
{
    *strDsn = new char[iLen + 1]; // update the ptr value. + 1 for null terminator.

    for (int i=0; i< iLen; i++)
        *strDsn[i] = strSrc[i]; // index painfully (would be look nicer with a temp variable).

}

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); // pass the address of mystrDsn

    printf(mystrDsn);
    return 0;
}

Upvotes: 2

Related Questions