Menu
Coddy logo textTech

Recap: Dynamic String Concat

Part of the Logic & Flow section of Coddy's C journey — lesson 61 of 63.

challenge icon

Challenge

Easy

Create a C program that implements a dynamic string concatenation function to build a text processing utility. Your program should:

  1. Write a function named concatenateStrings that:
    • Takes two char* parameters named str1 and str2
    • Returns a char* pointing to a dynamically allocated string
    • Calculates the total memory needed for both strings plus the null terminator
    • Uses malloc() to allocate the exact amount of memory required
    • Checks if memory allocation was successful (returns NULL if allocation fails)
    • Uses strcpy() to copy the first string into the allocated memory
    • Uses strcat() to append the second string to the result
    • Returns the pointer to the newly created concatenated string
  2. Write a function named processText that:
    • Takes three char* parameters: word1, word2, and separator
    • Returns a char* pointing to a dynamically allocated string
    • Creates a combined string in the format: word1 + separator + word2
    • First calls concatenateStrings to combine word1 and separator
    • Then calls concatenateStrings again to append word2 to the result
    • Properly frees any intermediate memory allocations
    • Returns the final concatenated result
  3. In the main function:
    • Declare three character arrays of size 50 each: firstWord, secondWord, and connector
    • Read three strings from input representing the first word, second word, and connector
    • Call the processText function with these three strings
    • Check if the returned pointer is not NULL
    • If successful, print the result in this exact format: Result: [concatenated_string]
    • If memory allocation failed, print: Memory allocation failed
    • Calculate and print the length of the result string in this exact format: Length: [length]
    • Free the dynamically allocated memory

This challenge tests your mastery of dynamic memory allocation, string manipulation functions, pointer return values, and proper memory management. You'll practice calculating memory requirements, using malloc() and free(), working with multiple string functions, and handling memory allocation failures. The challenge demonstrates how dynamic allocation allows functions to create and return data that persists beyond their scope.

Try it yourself

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// TODO: Write your concatenateStrings function here

// TODO: Write your processText function here

int main() {
    // Read input
    char firstWord[50];
    char secondWord[50];
    char connector[50];
    
    scanf("%s", firstWord);
    scanf("%s", secondWord);
    scanf("%s", connector);
    
    // TODO: Write your code below
    // Call processText function and handle the result
    
    return 0;
}

All lessons in Logic & Flow