alt alt - 3 months ago 7
C Question

C function using strcat with strings

I'm trying to learn C. So I've challenged myself to create a function called

two()
which will effectively "double" a string.

two("foo") // => "foofoo"


But I'm having trouble using
strcat()
in conjunction with pointers. Here's what I have:

char *two(char *foo);

int main() {
printf("The value of two(\"foo\") is %s", two("foo"));
}

char *two(char *foo) {
return strcat(foo, foo);
}


It compiles but errors on run. Why?

I have a feeling the error resides in using
strcat
with pointer strings.

Answer

You didn't allocate space to hold two copies of your input string.

strcpy copies strings.

strcat appends one string onto another.

malloc allocats bytes on the heap that should be free() later.

char *two(char *foo);

int main() {
    char * ptr =  two("foo");
    printf("The value of two(\"foo\") is %s", ptr);
    free(ptr);
}

char *two(char *foo) {
    char * ptr = malloc(strlen(foo) * 2 + 1);
    strcpy(ptr, foo);
    strcat(ptr, foo);
    return ptr;
}
Comments