I want to get the length of an array, say int array[] = {1, 2, 3, 4}. I used sizeof to do that.
int length(int array[])
{
return sizeof(array) / sizeof(int);
}
int main()
{
int array[] = {1, 2, 3, 4};
printf("%d\n", length(array)); // print 1
printf("%d\n", sizeof(array) / sizeof(int)); // print 4
}
So, why the sizeof(array) in function length returns the pointer size of array? But in function main, it works.
And, how should I modify the length function to get an array’s length?
A special C rule says that for function parameters, array types are adjusted to pointer types. That means:
int length(int array[]);is equivalent to
int length(int *array);So when you compute the
sizeofthe array you are actually computing the size of the pointer.