The function myFunction
allocates A
, but this allocation only exists within the scope of the function. When the function returns the memory holding A
is destroyed. This means that the function is returning a pointer to memory that has not been un-allocated.
The problem is that the variable A
does not persist outside the function. You could use a global variable or pass a pointer to the buffer into myFunction
Global variable method:
static int A[3];
int* myFunction()
{
A[0] = 1; A[1] = 2; //etc
return A;
}
In this example, because A
is a global, the memory pointed to by A
persists throught your program's entire life time. Therefore it is safe to return a pointer to it...
As a side note, global variables should probably not be used in this way... it's a little clunky. The use of the static
keyword means that A
will not be accessible outside of this module (C file).
Pointer method:
void myFunction(a[3])
{
a[0] = 1; a[1] = 2; //etc
}
int main()
{
myA[3];
myFunction(myA);
// and continue to print array...
}
In this example the main()
function allocates myA
. This variable exists whilst the function is executing (it's an automatic variable). A pointer to the array is passed into the function, which fills the array. Therefore the main()
function can get information from myFunction()
.
Another way to make the variable myA
persist would be to allocate it on the heap. To do this you would do something like int *myA = malloc(sizeof(int) * NUMBER_OF_INTS_IN_ARRAY
. This memory will then persist until you specifically desctroy it using free()
or you program ends.