Reputation: 6463
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;
}
Upvotes: 0
Views: 945
Reputation: 29983
What you are observing is Undefined Behavior, because the array that was created in memory_alloc
only exists in this function's scope. Once the program leaves it, that array will no longer exist.
An alternative is to allocate the array in the heap:
int memory_alloc()
{
int *array = malloc(ARR_SIZE * sizeof(int));
int i = 0;
for(i; i < ARR_SIZE; i++)
{
array[i] = i;
}
return array;
}
After you're done using the array, it should be freed.
int main()
{
int* array_pointer = memory_alloc();
// use array here
free(array_pointer);
return 0;
}
Upvotes: 2
Reputation: 25875
int array[ARR_SIZE];
here integer array is local to function and it will not longer available after function end.
To make it work you can do like
static int array[ARR_SIZE];
And
return array; //no need &
Upvotes: 1
Reputation: 12270
the array that you are declaring in memory_alloc() function
int array[ARR_SIZE];
this array is a local variable. its scope is within the function memory_alloc() and as soon as this function returns, all the local variables are destroyed (so is your array[])
instead, declare the array in main(), and pass the array to memory_alloc().
Upvotes: 1