Hey guys I’m trying to figure how pointers are returned by strcat(), so I tried implementing my own strcat() to see how it works. The following is my code for mystrcat(), which works like the real strcat():
char *mystrcat(char *destination, char *source)
{
char *str = destination;
while (*str != '\0')
{
str++;
}
while (*source != '\0')
{
*str = *source;
str++;
source++;
}
*str = '\0';
return str;
}
So let’s say in my main(), I have
char string[BUFSIZ];
mystrcat(string, "hello");
printf("%s\n", string);
The output would be
hello
as expected. What I don’t get is how returning the address of the local variable, str, would magically make the variable, string, point to it and also why is the variable, str, not deleted when the function terminates.
You’re not returning the address of the local variable. You’re returning the value of the local variable. Since the variable in question is a pointer, its value happens to be an address. The address that is contained in the
strvariable points into the memory block provided by the argumentdestination.What you seem to be misunderstanding is that this:
Does not create a copy of the
destinationstring. It creates a pointer calledstrthat points at the same memory location thatdestinationpoints to. When you usestrto manipulate the characters in that memory block, the string represented bydestinationis also modified, becausestranddestinationpoint into the exact same string of characters in memory. That’s how it “magically updates” the parameter.