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
destwhich 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
printffor*destin your loop is useless; you’ve already incrementeddestat that point, so it points to the next unused location. (Theprintfcall forsourcealso prints the next character to be copied, not the one you just copied.)As an aside, it’s unclear what you intend
sizeto 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.