Search code examples
cpointersfunction-pointersc-stringsstring-concatenation

C program to concatenate two pointer strings with functions


#include <stdio.h>
#include <stdlib.h>
    
char concaten(const char *str1,const char *str2);
    
int main()
    {
        printf("%s",concaten("Code","blocks"));
        return 0;
    }
    
char concaten(const char *str1,const char *str2) {
    int i=0,j=0;
    char *result;
    while(*str1){
        result[i++]=str1[i++];
    }
    while(*str2){
        result[i+j++]=str2[j++];
    }
    return result;
}

I wrote this function to get two strings and add them to another third string; I don't understand where I am going wrong, as it doesn't print anything.


Solution

  • There are a number of problems with your concaten function.

    First, it should be returning a char* pointer, not a char; thus, the declaration should look like this:

    char* concaten(const char* str1, const char* str2);
    

    Next, the function will need to allocate memory in which to store the concatenated strings; this can be done with the malloc() function, and the number of characters required will be the sum of the lengths of the two input strings plus one, for the required nul-terminator.

    Third, the logic of your two loops is wrong. You are incrementing i and j twice per loop but not incrementing either of the source pointers.

    Finally, you must add a nul-terminator at the end of your new string.

    Here's a version with the above fixes applied:

    char* concaten(const char* str1, const char* str2)
    {
        int i = 0, j = 0;
        char* result = malloc(strlen(str1) + strlen(str2) + 1); // allow space for nul-terminator
        while (*str1) {
            result[i++] = *str1++; // Only increment i once and "str1" once
        }
        while (*str2) {
            result[i + j++] = *str2++; // Only increment j once and "str2" once
        }
        result[i + j] = '\0'; // Add required nul-terminator
        return result;
    }
    

    Also, as you have allocated memory (with the malloc call), you should release that when you're done with the data, using a call to free. Here's how your main might work:

    int main(void)
    {
        char* answer = concaten("Code", "blocks");
        printf("%s", answer);
        free(answer);
        return 0;
    }
    

    Note: You can also remove the j variable entirely, and just re-use the result[i++] expression in the second loop. I've left it in so that you can more easily relate my code to your own.