This question already has an answer here:
- size of array in c 6 answers
How can I obtain the number of elements present in an integer array in C after the array is passed to a function? The following code doesn't work.
size=sizeof(array)/sizeof(array[0]);
In C, you can only get the size of statically allocated arrays, i.e.
would give 10.
If your array is declared or passed as
int* array
, there is no way to determine its size, given this pointer only.You are most likely doing this inside the function to which you pass the array.
The array decays as pointer to first element So You cannot do so inside the called function.
Perform this calculation before calling the function and pass the size as an function argument.
You are going about it in the wrong way. I'll try to explain using a small code example. The explanation is in the code comments:
As you can see from the code above you shouldn't use
sizeof
to find how many elements there are in an array. The correct way to do it is to have one (or two) variables to keep track of the size.