简体   繁体   中英

Copying a C-style string into memory allocated on free store?

I'm doing an exercise in which I have to copy a c-style string into memory allocated on free store. I am required to do it without using subscripting and relying solely on pointer arithmetic. I wrote the following function-

char* str_dup(const char* s)
{
    // count no. of elements
    int i = 0;
    const char* q = s;
    while (*q) { ++i; ++q; }

    //create an array +1 for terminating 0
    char* scpy = new char[i + 1];

    //copy elements to new array
    while (*s)
    {
        *scpy = *s;
        ++s;
        ++scpy;
    }
    *scpy = 0;
    return scpy;
}

The function is returning random characters. But if I change it into this-

char* str_dup(const char* s)
{
    // count no. of elements
    int i = 0;
    const char* q = s;
    while (*q) { ++i; ++q; }

    //create an array +1 for terminating 0
    char* scpyx = new char[i + 1];
    char* scpy = scpyx;

    //copy elements to new array
    while (*s)
    {
        *scpy = *s;
        ++s;
        ++scpy;
    }
    *scpy = 0;
    return scpyx;
}

it works. Can someone explain me why first code is not working and second is working?

The first code is not working since you return the final value of scpy , which at that point points at the terminating NUL character, and not the start of the string.

One solution is to do as you did, and save a copy of the original pointer to have something to return.

You should really use strlen() and memcpy() , they make this easier but perhaps they're off-limits to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM