Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to iterate through an array without knowing the size in c [duplicate]

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?

like image 446
a_confused_student Avatar asked Oct 31 '25 18:10

a_confused_student


1 Answers

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.

like image 165
chqrlie Avatar answered Nov 02 '25 11:11

chqrlie