Reputation: 16724
I'm writing a function that returns the size of ints array. The logic is: sizeof(arr) / sizeof(int);
it worked fine if I save it to an variable, but if I return it to a function, I get 1
for an array with 10 bytes of size. Why? here is my code:
int b[10];
int t1= sizeof (b) / sizeof (int);
size_t t2 = lenof(b);
printf("t1 = %d, t2 = %d\n", t1, t2);
size_t lenof (int arr[]) { return sizeof (arr) / sizeof (int); }
the above C code prints:
t1 = 10, t2 = 1
someone can explain for me please? maybe should I do it using pointers? Thanks.
Upvotes: 0
Views: 116
Reputation: 206546
Scenario 1:
int t1= sizeof (b) / sizeof (int);
In this case, sizeof(b)
returns the size of the array, which divided by the size of int
yields number of array elements correctly.
Scenario 2:
When you pass array to a function it decays as a pointer to the first element in the array.Hence,
lenof(int arr[])
is actually exactly equivalent to:
lenof(int *arr)
GIven that, sizeof (arr)
yields size of an pointer on your system & that size it seems is same as size of int
on your system and hence the division and the function returns 1
.
C does not provide bounds checking for arrays, So you will never be warned if you write beyonds the array bounds. This essentially means wheile using arrays, You have to keep track of how many elements are present in the array yourself.
If you need the size of array inside a function simplest solution is to pass the size of the array as a separate parameter.
lenof(int arr[], int len);
Upvotes: 2