|
I understand that the reason the ret variable will not print (it's at the end of the string when destination is passed) but can't figure out how to return destination out of the my_strcpy() function. I can make this work using array notation but not pointer arithmetic. Here's the code in question:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *my_strcpy(char *, const char *);
int
main()
{
char *strA = "This is a string";
char *strB;
char *ret;
strB = malloc(strlen(strA)+1);
ret = my_strcpy(strB, strA);
puts(ret);
puts(strB);
free(strB);
return 0;
}
char *my_strcpy(char *destination, const char *source)
{
while (*source != '\0')
{
*(destination++) = *(source++);
}
*destination = '\0';
return destination;
}
|
|
|
|
|
Just use a local variable for copying or save the value of destination in a local variable to be returned upon exit:
char *my_strcpy(char *destination, const char *source)
{
char *ret = destination;
while (*source != '\0')
{
*destination++ = *source++;
}
*destination = '\0';
return ret;
}
|
|
|
|
|
In addition to Jochen's comments, you also need to allocate some memory to strB before calling your copy function. The code above will be copying into some random place and probably crash.
One of these days I'm going to think of a really clever signature.
|
|
|
|
|
He allocates memory using malloc() . You may have overlooked the line just above the copy call.
|
|
|
|
|
Oops!
One of these days I'm going to think of a really clever signature.
|
|
|
|