Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading