So I have to make a function to concatenate two strings in C; The function creates a new string by concatenating str1 and str2. The function has to call malloc() or calloc() to allocate memory for the new string.The function returns the new string.
After executing the following call to printf() in a main test function: printf ( “%s\n”, myStrcat( “Hello”, “world!” )); the printout on the screen has to be Helloworld!
Here's my code so far; I can't quite understand why it does not work. It doesn't do anything... it compiles and runs but nothing is displayed.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *my_strcat( const char * const str1, const char * const str2);
int main()
{
printf("%s", my_strcat("Hello", "World")); // test function. Output of print statement is supposed to be HelloWorld
}
char *my_strcat( const char * const str1, const char * const str2)
{
char *temp1 = str1; // initializing a pointer to the first string
char *temp2 = str2; // initializing a pointer to the second string
// dynamically allocating memory for concatenated string = length of string 1 + length of string 2 + 1 for null indicator thing.
char *final_string = (char*)malloc (strlen(str1) + strlen(str2) + 1);
while (*temp1 != '\0') //while loop to loop through first string. goes as long as temp1 does not hit the end of the string
{
*final_string = *temp1; // sets each successive element of final string to equal each successive element of temp1
temp1++; // increments address of temp1 so it can feed a new element at a new address
final_string++; // increments address of final string so it can accept a new element at a new address
}
while (*temp2 != '\0') // same as above, except for string 2.
{
*final_string = *temp2;
temp2++;
final_string++;
}
*final_string = '\0'; // adds the null terminator thing to signify a string
return final_string; //returns the final string.
}
mallocin C.*final_string = '\0'; return final_string;<--- Look at what you're returning, here.