开发者

How does return of pointer work in strcat()

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];
mystrca开发者_开发知识库t(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 str variable points into the memory block provided by the argument destination.

What you seem to be misunderstanding is that this:

char* str = destination;

Does not create a copy of the destination string. It creates a pointer called str that points at the same memory location that destination points to. When you use str to manipulate the characters in that memory block, the string represented by destination is also modified, because str and destination point into the exact same string of characters in memory. That's how it "magically updates" the parameter.


str is a pointer to the string you pass in (destination), so you are modifying your original variable string from within your strcat function.

The pointer str does get deleted at the end of the routine, but it is not needed anymore.

BTW, it is confusing to use the word "string" as the name of a variable, because many languages reserve string as a keyword.


The first line of the function, you're assigning *str to be the same as *destination. In effect, when you return, you're returning *destination, which is the same as *str.

No memory is allocated, so no memory must be deleted.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜