The problem is the following line:
scanf ("%d", array_pp[i]);
The expression array_pp[i]
would be correct if array_pp
was a pointer to the first element of an array. However, it is a pointer to a single variable of type int *
. Since a single variable is equivalent to an array of size 1, the only permissible index that is not out of bounds would be array_pp[0]
. However, for single variables, it is common to write *array_pp
instead, even if it accomplishes exactly the same thing as array_pp[0]
. This is because indexing is generally only used with "proper" arrays, i.e. arrays with at least 2 elements.
The expression *array_pp
(or array_pp[0]
if you prefer) gives you access to the variable
int *array_p
from the function main. Since that pointer now points to the first element of a dynamically allocated array of type int
, you can use the indexes 0
to size
on that pointer. So you could write either
(*array_pp)[i]
or
array_pp[0][i]
in your loop, where i
is a value between 0
and size
.
As stated before, even if both expressions accomplish exactly the same thing, it is better to write (*array_pp)[i]
instead of array_pp[0][i]
.
However, the function scanf()
requires the address of the array element to write to. So the line should be changed to the following:
scanf ("%d", &(*array_pp)[i]);