al3x4nder wrote:
look this code:
#include <stdio.h>
#define length(arr) sizeof(arr)/sizeof(arr[0])
void func(int arr[]){
printf("func(): length(arr) = %d\n", length(arr));
}
void main(void){
int i, arr[] = {1,2,3};
printf("main(): length(arr) = %d\n", length(arr));
func(arr);
}
and, please, explain me, why length() macro
works with differences in different context?
stupid question? oh...
When you pass an array as a parameter to a function you're really
passing a pointer to its first element. In fact when an array is used
in an expression except as the operand of the sizeof or the & operator,
the array identifier allways decays into a pointer to the first element
of the array, including when the arrays is one parameter in a function
call.
The declaration of func you gave is totally equivalent to:
void func (int *arr)
[...]
Inside the function arr is of type int*, not of type int[3]. So inside
the function, the macro evaluates to:
length(arr) = sizeof(arr) / sizeof(arr[0]) = sizeof (int*) / sizeof
(int) = some value that will vary from implementation to
implementation. 1 & 2 are usual values, but you can expect about
anything.
In main the macro expands to:
length(arr) = sizeof(arr) / sizeof(arr[0]) = sizeof (int[3]) / sizeof
(int) = 3 irregardless of implementation
HTH