Do you have to manually loop through the array once and get a count of the strlen of each character array, sum it, allocate destination with the summed value and then loop over the array again?
How do you find the size of the array that contains the arrays of characters so you can iterate over them?
How do you find the size of the array that contains the arrays of characters so you can iterate over them?
There are two ways:
char*
at the end of the array and store a null pointer in it as a sentinel, similar to the way a NUL character is used to terminate a string.In other words, you have to do your own bookkeeping when allocating the array because C won't give you the desired information. If you follow the second suggestion, you can get the total number of characters in the array of strings with
size_t sum_of_lengths(char const **a)
{
size_t i, total;
for (i = total = 0; a[i] != NULL; i++)
total += strlen(a[i]);
return total;
}
Don't forget to reserve space for a '\0'
when doing the actual concatenation.
I assume you are trying to make a string that is the concatenation of all of the strings in the array.
There are 2 ways of doing this:
Make 2 passes as you suggest, summing the lengths in the first pass, allocating the destination string, and then appending the strings in the second pass
Make 1 pass. Start by allocating the buffer to some size. Append the strings, keeping track of the total size. If you don't have enough room for a string, reallocate the buffer with realloc()
. The most efficient method of reallocation will be to double the size of the buffer each time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With