Hello,
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;
}