how to join an array of strings c

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

char join_strings(const char* strings, int num_strings) {
    int total_length = 0;
    for (int i = 0; i < num_strings; ++i) {
        total_length += strlen(strings[i]);
    }

    char result = (char)malloc(total_length + 1);
    if (result == NULL) {
        return NULL;
    }

    int current_index = 0;
    for (int i = 0; i < num_strings; ++i) {
        int length = strlen(strings[i]);
        strcpy(result + current_index, strings[i]);
        current_index += length;
    }

    result[current_index] = '\0';
    return result;
}

int main() {
    const char* words[] = {"Hello", ", ", "world", "!"};
    int num_words = sizeof(words) / sizeof(words[0]);

    char* concatenated = join_strings(words, num_words);
    if (concatenated == NULL) {
        printf("Memory allocation failed.\n");
        return 1;
    }

    printf("Concatenated string: %s\n", concatenated);

    free(concatenated); // Free allocated memory
    return 0;
}

This C code includes a function join_strings that concatenates an array of strings into a single string. Here's an explanation of each step:

  1. Header Files: #include <stdio.h>, #include <stdlib.h>, and #include <string.h> are included for standard input/output operations, memory allocation, and string manipulation functions.

  2. join_strings Function: This function takes an array of strings (const char strings) and the number of strings (int num_strings) as parameters and returns a concatenated string.

a. total_length variable is initialized to calculate the total length required for the concatenated string by summing up the lengths of each individual string in the array.

b. Memory is allocated for the result string using malloc based on the total length calculated plus one extra space for the null terminator '\0'.

c. The function iterates through each string in the array, copying each string into the result string at the appropriate position using strcpy. The current_index keeps track of the position where the next string should be copied.

d. Finally, the null terminator '\0' is placed at the end of the concatenated string.

  1. main Function:

a. An array of strings words is declared, containing "Hello", ", ", "world", and "!".

b. num_words is calculated by dividing the total size of the words array by the size of an individual element.

c. The join_strings function is called with the words array and num_words as arguments to concatenate the strings.

d. If memory allocation fails, an error message is printed, and the program returns 1 indicating failure.

e. If the concatenation is successful, the concatenated string is printed using printf.

f. Finally, the memory allocated for the concatenated string is freed using free to prevent memory leaks.