-4

i want to get the number of elements at Text array the answer should be 2

char Text[5][10] = {
    "Big12345",
    "Big54321",
};

i want to a code to count number of elements in array of chars

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335

3 Answers3

1

You are mistaken. The number of elements in the array is 5. Two elements have non-empty strings and three elements have empty strings. But In fact an empty string can be placed anywhere in the array. For example

char Text[5][10] = 
{
    "Big12345",
    "",
    "Big54321",
};

This declaration is equivalent to

char Text[5][10] = 
{
    "Big12345",
    "",
    "Big54321",
    "",
    ""
};

You could write a function that determines how many elements contain non-empty strings. For example

#include <stdio.h>

size_t count_non_empty( size_t m, size_t n, char s[][n] )
{
    size_t count = 0;

    for ( size_t i = 0; i < m; i++ )
    {
        count += s[i][0] != '\0';
    }

    return count;
}

int main(void) 
{
    char Text[5][10] = 
    {
        "Big12345",
        "",
        "Big54321",
    };

    printf( "There are %zu non-empty elements\n", count_non_empty( 5, 10, Text ) );

    return 0;
}

The program output is

There are 2 non-empty elements
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

In this particular case, anything after the initializers will be 0, so:

size_t counter = 0;

while ( Text[counter][0] != 0 )
  counter++;

But, in general, C doesn't give you a good way of doing this. You either have to track the number of elements being used separately, or you have to use a sentinel value in the array.

John Bode
  • 119,563
  • 19
  • 122
  • 198
0

Use the following to find the number of elements in your array which have a string assigned to them:

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

int main()
  {
  char Text[5][10] = {"Big12345",
                      "Big54321",};
  int i, n;

  for(i = 0, n = 0 ; i < 5 ; i++)
    if(strlen(Text[i]) > 0)
      n += 1;

  printf("%d elements have a length > 0\n", n);

  return 0;
  }
  • Detail: All elements of `Text[]` have a _string_ in them as the empty `""` is a _string_. – chux - Reinstate Monica Apr 16 '20 at 16:03
  • Rather than call the function and find the length by iterating the length of the string, `if(Text[i][0] != 0)` would be sufficient. – chux - Reinstate Monica Apr 16 '20 at 16:06
  • @chux-ReinstateMonica - I considered that but figured someone would then determine that I should have used `strlen` to obtain the length of a string rather than depending on an implementation artifact. This is, after all, C - where every answer is, to some degree, from some point of view, wrong. (And if you can't find anything wrong with the answer you can always complain about the indentation scheme the author used :-). – Bob Jarvis - Слава Україні Apr 16 '20 at 16:13
  • 1
    `if(Text[i][0] != 0)` does not use any “implementation artifact.” – Eric Postpischil Apr 16 '20 at 16:28