Why isn't the size of an array sent as a parameter the same as within main?
#include <stdio.h> void PrintSize(int p_someArray[10]); int main () { int myArray[10]; printf("%d\n", sizeof(myArray)); /* As expected, 40 */ PrintSize(myArray);/* Prints 4, not 40 */ } void PrintSize(int p_someArray[10]){ printf("%d\n", sizeof(p_someArray)); }
If you create an array by initializing its values directly, the size will be the number of elements in it. Thus the size of the array is determined at the time of its creation or, initialization once it is done you cannot change the size of the array.
The main difference between Array and ArrayList in Java is that Array is a fixed length data structure while ArrayList is a variable length. You can not change length of Array once create, but ArrayList can re-size itself.
Passing the array size tells the function where the bounds are so you can choose not to go beyond them.
Because fixed arrays have memory allocated at compile time, that introduces two limitations: Fixed arrays cannot have a length based on either user input or some other value calculated at runtime. Fixed arrays have a fixed length that can not be changed.
An array-type is implicitly converted into pointer type when you pass it in to a function.
So,
void PrintSize(int p_someArray[10]) { printf("%zu\n", sizeof(p_someArray)); }
and
void PrintSize(int *p_someArray) { printf("%zu\n", sizeof(p_someArray)); }
are equivalent. So what you get is the value of sizeof(int*)
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