I have a pointer to an array in C which I would like to iterate through, but I don't know the size:
int *array;
I am unsure as to how I should proceed. I was thinking that I should probably try by finding the size by doing:
int array_size = sizeof(array) / sizeof(int);
But I don't know if that could work. I was wondering if there was a more optimal way of doing this?
In C, there is no way to tell the number of elements in an array from a pointer to an element. sizeof(array) / sizeof(*array) only works for an actual array, not for a pointer, which is what a function receives as an argument, even if the array syntax is used in the function prototype. In this case sizeof(array) evaluates to the size of the pointer, so dividing that by the size of an element is meaningless.
The best approach for your function to get the number of elements is to provide it as a separate argument.
If this is not practical, there are different ways to infer the number of elements, relying on a convention that must be adhered to by the callers:
the array could have a known fixed number of elements
the array could have a sentinel value as the last element of the array.
It is common to use a null pointer (NULL) as such a sentinel for arrays of pointers, such as the char *argv[] argument of the main() function, but note that int argc is also provided to this function.
The null byte (\0) is used to tell the end of C strings, which are arrays of char.
In your case, you could consider 0 or -1 to signify the end of the array, but this convention must be used consistently by all callers of your function.
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