Complementary task for topic: 7
M Nemeth · 2023-08-29 15:21:04.624218'
DStrings: Concatenate Two Dynamic Strings
DStrings: Concatenate Two Dynamic Strings
Create a C program that reads two strings from the user and concatenates them into a single dynamic string. The dynamic string is created inside a function and passed back to the main function.
Hint: Use dynamic memory allocation to create the dynamic string inside a function.
Prompt the user to enter two strings.
Pass the strings to a function to concatenate them into a single dynamic string.
Return the dynamic string from the function and display it in the main function.
Deallocate the memory used by the dynamic string.
Solution
#include
#include
#include
char* concatenateStrings(const char* str1, const char* str2) {
int len1 = strlen(str1);
int len2 = strlen(str2);
char* result = (char*)malloc((len1 + len2 + 1) * sizeof(char));
if (result == NULL) {
printf("Memory allocation failed.\n");
exit(1);
}
strcpy(result, str1);
strcat(result, str2);
return result;
}
int main() {
char firstString[100];
char secondString[100];
char* concatenatedString;
printf("Enter the first string: ");
scanf("%99[^\n]", firstString); // Limit the input to 99 characters and exclude newline
printf("Enter the second string: ");
scanf(" %99[^\n]", secondString); // Limit the input to 99 characters and exclude newline
concatenatedString = concatenateStrings(firstString, secondString);
printf("Concatenated string: %s\n", concatenatedString);
// Deallocate the memory used by the dynamic string
free(concatenatedString);
return 0;
}
Explanation
The program defines a function concatenateStrings() that takes two constant strings (str1 and str2) as arguments and returns a dynamic string (char pointer) that is the result of concatenating the two input strings. Inside the concatenateStrings() function, we first calculate the lengths of the two input strings using strlen() and add 1 to account for the null terminator. We then allocate memory for the result dynamic string using malloc() based on the total length required. We copy the first string to the dynamic string using strcpy() and then concatenate the second string using strcat(). The function returns the dynamic string containing the concatenated result. In the main function, the user is prompted to enter two strings using scanf("%99[^\n]", ...) for input (limiting it to 99 characters to prevent buffer overflow). The concatenateStrings() function is called with the two strings, and the returned dynamic string is stored in concatenatedString. The concatenated string is then displayed using printf(). Finally, the memory used by the dynamic string is deallocated using free() to avoid memory leaks.