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:
Then you can print all fruits like this:
As to why your original while loop failed:
idoesn’t get incrementedfruits[i] != '\0'wherefruits[i]is a pointer tocharand'\0'is acharequal to 0. So you are essentially checking iffruits[i]points to 0 but for the first three iterations this is not the case asfruits[i]points to the first character of the respective fruit and in the fourth iterationfruits[i]points to a memory location that doesn’t belong to your program.