In my attempt to learn a bit about pointers, I tried to create a program that allocates memory for an array of given size (where the size is defined by the value of the constant ARR_SIZE) and prints out elements of that array to the console.
I cannot understand the results I am getting... For example, when I run the code shown below, I get {0, 4206628, 4206628, 3, 4, 5, 6, 2686696, 8, 9}, which makes absolutely no sense to me. I would like to know what is the reason of such behaviour and what to modify in order to obtain the anticipated results.
#define ARR_SIZE 10
void print_array(int loc);
int memory_alloc();
int main()
{
int array_loc = memory_alloc();
print_array(array_loc);
return 0;
}
void print_array(int loc)
{
int i = 0;
int *arr_ptr;
arr_ptr = loc;
while(i < ARR_SIZE)
{
printf("%d\n", *arr_ptr);
*(arr_ptr++);
i++;
}
}
int memory_alloc()
{
int array[ARR_SIZE];
int i = 0;
for(i; i < ARR_SIZE; i++)
{
array[i] = i;
}
return &array;
}