#include "stdio.h"
#define COUNT(a) (sizeof(a) / sizeof(*(a)))
void test(int b[]) {
printf("2, count:%d\n", COUNT(b));
}
int main(void) {
int a[] = { 1,2,3 };
printf("1, count:%d\n", COUNT(a));
test(a);
return 0;
}
The result is obvious:
1, count:3
2, count:1
My questions:
- Where is the length(count/size) info stored when “a” is declared?
- Why is the length(count/size) info lost when “a” is passed to the test() function?
There’s no such thing as “array pointer” in C language.
The size is not stored anywhere.
ais not a pointer,ais an object of typeint[3], which is a fact well known to the compiler at compile time. So, when you ask the compiler to calculatesizeof(a) / sizeof(*a)at compile time the compiler knows that the answer is3.When you pass your
ato the function you are intentionally asking the compiler to convert array type to pointer type (since you declared the function parameter as a pointer). For pointers yoursizeofexpression produces a completely different result.