The problem is here:
scanf("%d", (integersArray[i]));
Remember, integersArray
is a pointer to the array. In other words, it is a pointer to a pointer to the first element in the array.
Instead try:
scanf("%d", &(*integersArray)[i]);
First, since integersArray
is a pointer to the int array, I dereference it: (*integersArray)
.
Then, I index to the i
th element in the array: (*integersArray)[i]
.
But, scanf
expects the address of the integer which gets the result, I take the address of that element: &(*integersArray)[i]
.
The important thing to remember is that you must dereference integersArray
first.
Confirmed with gcc 4.8.2 i686-pc-cygwin
.
Here's what should be happening, and indeed happens (by luck!) on the first iteration.
______
integersArray ---> <malloc_result> ---> |______|
|______|
|______|
|______|
However, on the second iteration, the wrong pointer is being indexed, like this:
______
integersArray -| <malloc_result> ---> |______|
| |______|
| |______|
| |______|
|
|-> <malloc_result+4> ---> ?????????