C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Dynamic Memory Allocation in C

Dynamic string concatenation

C Program: Dynamic String Concatenation Using malloc() and realloc()n

C

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

 

int main() {

    char *str1, *str2, *result;

    int len1, len2;

 

    // Step 1: Input first string dynamically

    str1 = (char *)malloc(100 * sizeof(char));

    if (str1 == NULL) {

        printf("Memory allocation failed for str1!\n");

        return 1;

    }

    printf("Enter first string: ");

    fgets(str1, 100, stdin);

    str1[strcspn(str1, "\n")] = '\0';  // Remove newline character

 

    // Step 2: Input second string dynamically

    str2 = (char *)malloc(100 * sizeof(char));

    if (str2 == NULL) {

        printf("Memory allocation failed for str2!\n");

        free(str1);

        return 1;

    }

    printf("Enter second string: ");

    fgets(str2, 100, stdin);

    str2[strcspn(str2, "\n")] = '\0';  // Remove newline

 

    // Step 3: Calculate lengths

    len1 = strlen(str1);

    len2 = strlen(str2);

 

    // Step 4: Allocate memory for concatenated string

    result = (char *)malloc((len1 + len2 + 1) * sizeof(char));

    if (result == NULL) {

        printf("Memory allocation failed for result!\n");

        free(str1);

        free(str2);

        return 1;

    }

 

    // Step 5: Concatenate strings manually

    strcpy(result, str1);

    strcat(result, str2);

 

    // Step 6: Display result

    printf("\nConcatenated String: %s\n", result);

 

    // Step 7: Free allocated memory

    free(str1);

    free(str2);

    free(result);

 

    return 0;

}

Output

 
OUTPUT :
Enter first string: Hello
Enter second string: World

Concatenated String: HelloWorld

Explanation

Step

Description

1

Allocate memory dynamically for two input strings (str1 and str2).

2

Read input using fgets() to handle spaces.

3

Compute the lengths using strlen().

4

Allocate combined memory for result string = (len1 + len2 + 1) bytes.

5

Use strcpy() and strcat() to join them.

6

Print the concatenated result.

7

Free all memory using free().