Here is an alternate fix. First, you forgot #include <stdlib.h>
for malloc()
. You return a pointer to char
from the function my_strcat()
, so you need to change the function prototype to reflect this. I also changed the const
declarations so that the pointers are not const
, only the values that they point to:
char * my_strcat(const char *str1, const char *str2);
Your call to malloc()
is incorrectly cast, and there is no reason to do so anyway in C. It also looks like you were trying to cast the argument in malloc()
to size_t
. You can do so, but you have to surround the type identifier with parentheses:
a = malloc((size_t) s3);
Instead, I have changed the type declaration for s1, s2, s3, i
to size_t
since all of these variables are used in the context of string lengths and array indices.
The loops were the most significant change, and the reason that I changed the const
s in the function prototype. Your loops looked fine, but you can also use pointers for this. You step through the strings by incrementing a pointer, incrementing a counter i
, and store the value stored there in the i
th location of a
. At the end, the index i
has been incremented to indicate the location one past the last character, and you store a '\0' there. Note that in your original code, the counter i
was not incremented to indicate the location of the null terminator of the concatenated string, because you reset it when you looped through str2
. @jpw shows one way of solving this problem.
I changed main()
just a little. I declared a pointer to char
to receive the return value from the function call. That way you can free()
the allocated memory when you are through with it.
Here is the modified code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char * my_strcat(const char *str1, const char *str2)
{
size_t s1, s2, s3, i = 0;
char *a;
s1 = strlen(str1);
s2 = strlen(str2);
s3 = s1+s2+1;
a = malloc(s3);
while(*str1 != '\0') {
a[i] = *str1;
str1++;
i++;
}
while(*str2 != '\0') {
a[i] = *str2;
str2++;
i++;
}
a[i] = '\0'; // Here i = s1 + s2
return a;
}
int main(void)
{
char *str = my_strcat("Hello", "world!");
printf("%s\n", str);
/* Always free allocated memory! */
free(str);
return 0;
}