Complementary task for topic: 7

M Nemeth · 2023-08-29 15:21:04.624218'

DStrings: Concatenation

DStrings: Concatenation

Create a C program that reads two strings from the user and concatenates them into a single dynamic string. The program should allocate memory dynamically to hold the concatenated string.

Hint: Use dynamic memory allocation to create the dynamic string.
Prompt the user to enter two strings.
Concatenate the two strings into a single dynamic string.
Display the concatenated dynamic string as the output.
Deallocate the memory used by the dynamic string.

Solution
#include 
#include 
#include 

int main() {
    char* dynamicString = NULL;
    char firstString[100];
    char secondString[100];

    printf("Enter the first string: ");
    scanf("%99s", firstString); // Limit the input to prevent buffer overflow

    printf("Enter the second string: ");
    scanf("%99s", secondString); // Limit the input to prevent buffer overflow

    // Allocate memory for the dynamic string
    int totalLength = strlen(firstString) + strlen(secondString) + 1; // +1 for null terminator
    dynamicString = (char*)malloc(totalLength * sizeof(char));

    if (dynamicString == NULL) {
        printf("Memory allocation failed.\n");
        return 1;
    }

    // Concatenate the two strings into the dynamic string
    strcpy(dynamicString, firstString);
    strcat(dynamicString, secondString);

    // Print and use the dynamic string
    printf("Concatenated string: %s\n", dynamicString);

    // Deallocate the memory used by the dynamic string
    free(dynamicString);

    return 0;
}



Explanation
    The program defines a character pointer dynamicString to hold the dynamic string and two character arrays firstString and secondString to store the user input for the two strings.

    The user is prompted to enter the first string and the second string using printf() and scanf(). The scanf() function limits the input to 99 characters to prevent buffer overflow.

    The total length required for the dynamic string is calculated by adding the lengths of the two input strings plus one extra character for the null terminator.

    Memory for the dynamic string is allocated using malloc() based on the total length calculated.

    The strcpy() and strcat() functions from the string.h library are used to concatenate the two input strings into the dynamic string.

    The concatenated dynamic string is printed using printf().

    Finally, the memory used by the dynamic string is deallocated using free() to avoid memory leaks.
< < previous    next > >