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
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
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
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.
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;
}