Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you iterate over an array of character arrays in c?

Tags:

c

c-strings

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?

like image 704
Walt Avatar asked Jan 28 '12 17:01

Walt


2 Answers

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:

  1. Record the number of strings in the array when you allocate it in a variable.
  2. Allocate an extra 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.

like image 95
Fred Foo Avatar answered Sep 21 '22 07:09

Fred Foo


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:

  1. 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

  2. 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.

like image 22
Martin Broadhurst Avatar answered Sep 22 '22 07:09

Martin Broadhurst