1

I am tasked with writing a function that takes as an argument a char** and returns a char*. The char* must point to a null terminated string that is the concatenation of each of the strings in the char**.

How should I approach this?
Some places recommend looping through the char** and using strcat() to build the string, but strcat() requires that I have a destination large enough to hold the final string; and I don't know how large the string is going to be. Should I find out how large its going to be by asking for strlen() of each of the elements of the char**?

What's the best way to do this in C?

0

5 Answers 5

3

Possible approach:

  • Iterate over the char**, accumulating the result of strlen(char*) for each entry.
  • Add one to the accumulated length for the terminating null character.
  • Allocate memory for the string using malloc() and set first character to null terminator (to ensure strcat() functions correctly the first time).
  • Iterate again using strcat().

Document that the caller is responsible for free()ing the returned string.

Sign up to request clarification or add additional context in comments.

Comments

2

There are two main ways you can do this:

  • Do an initial pass over all the strings and do a sum of all the strlens
  • Start with a NULL string and iterate over the strings. As you iterate you realloc the destination to accomodate the increase in size

Comments

0

Yes you had better to calculate all the space needed so you can malloc enough space for the new string.

After creating the space for all strings, just copy them with a space character maybe between them (but if you add spaces, don't forget to count them for the allocation ...)

Comments

0

There is a function that does this in the library over here: http://sourceforge.net/projects/libxc/

The actual function is documented here

(Yes, I am the owner of that project, no I don't make money of it)

Comments

0

You may want to consider the following commented code (live here on Ideone.com).

In summary:

  1. Iterate through the input string array, computing the total length of the resulting string, summing the lengths of the input strings, using strlen().
  2. Allocate memory for the resulting string, using malloc().
  3. Iterate through the input array again, concatenating the input strings, using strcat().

#include <stdio.h>      /* For printf()             */
#include <stdlib.h>     /* For malloc(), free()     */
#include <string.h>     /* For strcat(), strlen()   */


/*
 * Concatenates input strings into a single string.
 * Returns the pointer to the resulting string.
 * The string memory is allocated with malloc(),
 * so the caller must release it using free().
 * The input string array must have NULL as last element.
 * If the input string array pointer is NULL, 
 * NULL is returned.
 * On memory allocation error, NULL is returned.
 */
char * ConcatenateStrings(const char** strings)
{
    int i = 0;              /* Loop index               */
    int count = 0;          /* Count of input strings   */
    char * result = NULL;   /* Result string            */
    int totalLength = 0;    /* Length of result string  */


    /* Check special case of NULL input pointer. */
    if (strings == NULL)
    {
        return NULL;
    }

    /* 
     * Iterate through the input string array,
     * calculating total required length for destination string.
     * Get the total string count, too.
     */
    while (strings[i] != NULL)
    {
        totalLength += strlen(strings[i]);
        i++;
    }
    count = i;
    totalLength++;  /* Consider NUL terminator. */

    /*
     * Allocate memory for the destination string.
     */
    result = malloc(sizeof(char) * totalLength);
    if (result == NULL) 
    {
        /* Memory allocation failed. */
        return NULL;
    }

    /*
     * Concatenate the input strings.
     */
    for (i = 0; i < count; i++) 
    {
        strcat(result, strings[i]);
    }

    return result;
}

/*
 * Tests the string concatenation function.
 */
int main(void)
{
    /* Result of string concatenation */
    char * result = NULL;

    /* Some test string array */
    const char * test[] = 
    {
        "Hello ",
        "world",
        "!",
        " ",
        "Ciao ",
        "mondo!",
        NULL                /* String array terminator */
    };

    /* Try string concatenation code. */
    result = ConcatenateStrings(test);

    /* Print result. */
    printf("%s\n", result);

    /* Release memory allocated by the concatenate function. */
    free(result);

    /* All right */
    return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.