开发者

Copying an array of characters

gcc 4.4.2 c89

I was just working on some pointers. However, with the program below I can't get it to copy the source to the destination. Even when I try and print in the for loop I can display the characters in开发者_运维百科 the source, but the dest is blank. When the pointer returns the destination is empty. So it hasn't copied anything.

I have been on this problem for about an hour, and its just not clear to me why its not working.

Any suggestions?

Many thanks,

char str_source[80] = "A string to be for demostration purposes";
char str_dest[80] = {0};

char *my_strncpy(char *dest, const char const *source, const size_t size)
{
    size_t i = 0;
    printf("size [ %d ]\n", size);

    for(i = 0; i < size; i++)
    {
        printf("i [ %d ]\n", i);

        *dest++ = *source++;
        printf("*source++ [ %c ]\n", *source);
        printf("*dest [ %c ]\n", *dest);
    }
    /* Null terminate */
    *dest++ = '\0';

    return dest;
}

=============== EDIT

char str_source[80] = "A string to be for demostration purposes";
char str_dest[80] = {0};

printf("str_dest [ %s ]\n", my_strncpy(str_dest, str_source, sizeof(str_dest)));


char *my_strncpy(char *dest, const char const *source, const size_t size)
{
    size_t i = 0;
    /*
     * increment p and return the dest which will be
     * the beginning of the array.
     */
    char *p = dest;

    /* Copy the specified amount (normally the max size of dest - 1) */
    for(i = 0; i < size; i++)
    {
    /* Ensure that the source is not overrun. */
    if(*source)
        *p++ = *source++;
    }
    /* Null terminate */
    *p++ = '\0';

    return dest;
}


Exactly how are you testing that the function doesn't work? Note that your function is returning dest which now points to the end of the destination buffer. Is the calling function checking the returned pointer, or is it checking the pointer it passed as the destination buffer?

For similar reasons, the printf for *dest in your loop is useless; you've already incremented dest at that point, so it points to the next unused location. (The printf call for source also prints the next character to be copied, not the one you just copied.)

As an aside, it's unclear what you intend size to be. If it's the number of bytes in the destination buffer, you could overflow the buffer when you write the NUL-terminator.

Oh, and you should check that you don't read past the end of source.


The problem is that the pointer which you are returning has been incremented and doesn't point to the begining. So, it shows as blank. Same appears to be the case for your for loop print also.

For Ex:

Let's say your initial destination address is 1000 and your source string size is 20, then your destnation returns 1020. But, it should actually be returning 1000.

Try storing the initial address of the destination in a local variable and returning that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜