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;
}
char array[10][100];has 10 elements. Those elements are arrays of 100 char. If you decide to initialize only 4 of them, then the number of initialized elements if 4 but the size is still 10. You don't need strlen or size; you initialized 4 of them so 4 of them are initialized. And the size remains 10. Don't compute anything at run time; this is entirely knowable at compile time, and doing any computation at runtime is wasted cycles. "As far as I know I'm not allowed to use ... sizeof". Well, that's just silly, since sizeof is the right operator if you don't want to hard-code 4 or 10