I have a pointer to an array in c to which I would like to iterate through but I don't know the size:
You are in luck if you truly have a pointer to an array as the type of a pointer to an array carries information about the array size.
int some_array[7] = {1, 2, 3, 4, 5, 6, 7};
int (*pointer_to_an_array)[7] = &some_array;
#define N (sizeof(*pointer_to_an_array) / sizeof(*pointer_to_an_array[0]))
for (size_t i = 0; i < N; i++) {
printf("%d\n", (*pointer_to_an_array)[i]);
}
Unfortunately, with int *array;
, code does not have a pointer to an array, but a pointer to an int
and information about the original array size of some_array[]
is not available through array
.
int some_array[7] = {1,2,3,4,5,6,7};
int *array = some_array; // Not a pointer to an array
Carry information about array size in another variable.
size_t some_array_n = sizeof some_array/ sizeof some_array[0];