I’m trying to teach myself programming and I’d really appreciate some help with this issue. I’ve just read a tutorial on pointers but I have a problem with the example. The function copies one string to another. In the original function a copy is being made with ptr. What is the meaning of this? because as far as I can see it’s unnecessary. Is there anything wrong with my revised function or am I missing something?
//Tutorial example
char *my_strcpy(char *destination, const char *source){
char *ptr = destination;
while(*source != ''){
*ptr++ = *source++;
}
*ptr = '';
return destination;
}
My revision
void my_strcpy2(char *destination, const char *source){
while(*source != ''){
*destination++ = *source++;
}
*destination = '';
}
Thanks.
2
From a technical point of view, using an additional variable ptr
to make it possible to return the original destination
value is unneccessary, since the caller obviously must already have the value of destination
in his scope. If you design a strcpy
-like function without returning that value, you can create a more comprehensive implementation, as you have shown above. But the original strcpy
function from the standard library is defined to return destination
, and my_strcpy
obviuosly tries to mimic that behaviour/signature.
The reason for this is mainly “syntactic sugar”, allowing the use of strcpy in a call chain. Read this SO post to get a better explanation for what it is good for.
To better understand the pointers I find it useful to put asterisk near the type, like char* destination
. This way you see that the value you pass has type “pointer to char” and you simply think of it as an integer (usually 32-bit or 64-bit) that in itself you may modify without any consequences. Your understanding is probably already good of this, because this is the reason a local copy is unnecessary. The case when with strcpy it is useful is to return the original value as noted by the other answer.