The count is returning unpredictable results. Sometimes they are right. Sometimes totally weird. Anyone can tell me what is wrong?
#include <stdio.h>
int len(int[]);
int main (int argc, const char * argv[])
{
int a[]={1,2,3,4,5,6,7,8};
int* i = a;
printf("length is %d",(len(i)));
return 0;
}
int len(int* a){
int count = 0;
for (; *a!='\0'; a++) {
count++;
}
return count;
}
I think you’re confused between C strings (arrays of
char) and other arrays. It’s a convention that C strings are terminated with a null character ('\0'), but not all arrays (evenchararrays) are terminated this way.The general convention is to either store the length of an array somewhere, or to use a sentinel value at the end of the array. This value should be one that won’t come up inside the array – eg
'\0'in strings, or-1in an array of positive ints.Also, if you know that
ais an int array (and not a pointer to an int array), then you can use:So you could do:
But you can’t do:
That last example will compile, but the answer will be wrong, because you’re getting the size of a pointer to the array rather than the size of the array.
Note that you also can’t use this
sizeofto read the size of an array that’s been passed into a function. It doesn’t matter whether you declare your functionlen(int *a)orlen(int a[])–awill be a pointer, because the compiler converts arrays in function arguments to be a pointer to their first element.