String concatenation in C

Hello,

I want to concatenate two string in C. could you please tell me where is my problem?
Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include<stdio.h>

int mystrlen(char *str)
{
    int i;
    for (i = 0; i < str[i] != '\0'; i++)
    {

    }
    return i;
}

void append(char* x, char* y)
{
    int lenX = mystrlen(x);
    int lenY = mystrlen(y);
    char *xy = (char*)malloc((lenY+lenX)*(sizeof(char)));
    for (int i = 0; i <  lenX; i++)
    {
        *xy++ = *x++;
    }
    for (int i = 0; i < lenY; i++)
    {
        *xy++ = *y++;
    }
    printf("%s", xy);
}

int main()
{
    char* x = "Hello";
    char* y = "World";

    append(x, y);

    return 0;
}
Inside your function you have at your printf() the xy-pointer at the end-position of your c-string. But this pointer needs to point to the begin of your c-string.
Last edited on
You need to have space for the end of string character and you need to insure that the array is properly terminated with that character.

Another big error is casting the return value from malloc(), that cast is "hiding" a serious problem being caused by not including a required header file.

The end condition in the loop in mystrlen is wacky, too.
x and y in main should be const, and so should the inputs to the functions.
xy is never freed.

Also, if all you want to do is print the strings right beside each other, you could just do:

 
printf("%s%s", x, y);

So maybe you want to return the allocated string instead.
Last edited on
Topic archived. No new replies allowed.