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?
The pointer is 8 bytes, because you are compiling for a 64bit system. The int it is pointing at is 4 bytes.
The sizeof() operator returns pointer size instead of array size. The 'sizeof' operator returns size of a pointer, not of an array, when the array was passed by value to a function. In this code, the A object is an array and the sizeof(A) expression will return value 100. The B object is simply a pointer.
The code calls sizeof() on a malloced pointer type, which always returns the wordsize/8. This can produce an unexpected result if the programmer intended to determine how much memory has been allocated. The use of sizeof() on a pointer can sometimes generate useful information.
The size of size_t and ptrdiff_t always coincide with the pointer's size. Because of this, it is these types that should be used as indexes for large arrays, for storage of pointers and pointer arithmetic. Linux-application developers often use long type for these purposes.
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 sizeof
the array you are actually computing the size of the pointer.
(C99, 6.7.5.3p7) "A declaration of a parameter as "array of type" shall be adjusted to "qualified pointer to type", where the type qualifiers (if any) are those specified within the [ and ] of the array type derivation."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With