Reputation:
As you can see in the code below I tried to print an array that I created in a different function. The output was totally different numbers compares to what I expected: numbers between 0 - 20 were set but I got some negative values.
So my question is why is this happening? And how to fix it if it even possible?
#include <stdio.h>
#include <time.h>
#define LEN 10
int* creatingArray();
void printingArray(int* array);
int main(void)
{
int* pointer_array = creatingArray();
printingArray(pointer_array);
getchar();
return 0;
}
int* creatingArray()
{
srand(time(NULL));
int array[LEN] = { 0 };
int* i = 0;
for (i = array; i < array + LEN; i++)
{
*i = rand() % 20;
}
return array;
}
void printingArray(int* array)
{
int* i = 0;
for (i = array; i < array + LEN; i++)
{
printf("\n%d\n", *i);
}
}
Upvotes: 0
Views: 87
Reputation: 58848
Pay attention to this code:
int* creatingArray()
{
// stuff
int array[LEN] = { 0 };
// more stuff
return array;
}
array
is a local variable, so it gets destroyed when the function returns. You then have a pointer to a destroyed variable. The space where it was will (most likely) continue to hold the data you put there - until the memory gets reused for something else and overwritten.
and how to fix it if it eve/n possible?
Several options:
Make array
a static
variable. Then it will not be destroyed when the function returns. (This also means that every time you call creatingArray
it will use the same array
, instead of a new one)
Make array
global.
Move array
to main
, and pass a pointer to it into creatingArray
, instead of having creatingArray
return one. Then, since it's a local variable in main
, it will only be destroyed when main
returns.
Use malloc
to allocate some space that will not be cleaned up automatically when the function returns.
Upvotes: 1