hardpenguin hardpenguin - 2 months ago 11
C Question

how to count string array elements in C?

I want my loop to repeat only as many times, as many are strings in "fruits" array.

Tried it first by using "while" loop, but I couldn't make it to work properly (now it is commented), because (as debugger showed) it segfaulted on 4th iteration. This method should work in array of chars or integers but does not work in array of strings. Why is it like this?

Then I tried to use "for" loop and wanted it to stop when reaching total number of string elements in array, stored in "count" variable. However, I could not find a good method to count number of strings in array. Is that even possible? "sizeof" operator doesn't seem like a good solution here.

Thanks in advance for response.

#include <stdio.h>

int main()
char *fruits[]={"Apple", "Grapefruit", "Banana"};
int i=0;
int count=sizeof(*fruits);

char **bitter=&fruits[1];

printf("Bitter fruit is: %s", *bitter);

puts(" ");

printf("All fruits are: ");

for (;i<count;i++);
printf("%s ",*(fruits+i));

while ( fruits[i] != '\0')
printf("%s ",*(fruits+i));

stuff above failed. why?

return 0;


An easy way would be to append a NULL to your list:

char *fruits[] = {"Apple", "Grapefruit", "Banana", NULL};

Then you can print all fruits like this:

int i = 0;
while (fruits[i] != NULL) {
    printf ("%s ",*(fruits+i));

As to why your original while loop failed:

  • your i doesn't get incremented
  • you are checking if fruits[i] != '\0' where fruits[i] is a pointer to char and '\0' is a char equal to 0. So you are essentially checking if fruits[i] points to 0 but for the first three iterations this is not the case as fruits[i] points to the first character of the respective fruit and in the fourth iteration fruits[i] points to a memory location that doesn't belong to your program.