Search code examples
arrayscstrlen

How to get array length for array of strings


I want to find the number of elements in that array, but as far as I know I'm not allowed to use strlen or sizeof. strlen(array[0]) gives out 5 cause apple consists of 5 characters, but I need length to equal to 4, because the arrays contains 4 words. Any suggestions?

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

int main() {
    char array[10][100] = {"apple", "banana", "strawberry", "grapefruit"};
    int length = strlen(array[0]);
    printf("%d", length);

    return 0;
}

Solution

  • You can search over array[i] until you find an empty string:

    size_t arrayLength = 0;
    for (size_t i=0; i<10; i++)
    {
      if (array[i][0] != '\0')
      {
        arrayLength++;
      }
      else
      {
        // with brace initialization, there will be no other words in the
        // array, we're safe to break
        break;
      }
    }
    

    When you use a brace-initialization list like that with a specified size, it will initialize the array to the contents you provided, and 0 for everything else. The pointers in the first dimension will still be valid (ie, array[i] is not-NULL for all i [0, 10) ), but they point to empty strings.

    Demonstration