You could say that there are two types of arrays: Statically allocated arrays, the ones you usually call arrays, and are declared like
double array[SOME_SIZE];
Then there's the second kind of array, which are allocated dynamically using e.g. malloc
(or in your case mkl_malloc
):
double *array = malloc(some_size);
The biggest difference between those two kind of arrays, is that for the first type of array it's allocated (usually) on the stack and that you can use sizeof
to get its size, and the second type is allocated on the heap and you need to keep track of its size yourself (and also free
it when done with it).
Both types can otherwise be used exactly the same, as arrays of the first type decays to pointers, and you can use array-indexing syntax with pointers.
The thing about returning pointers from functions is that if you declare the first type of array as a local variable inside a function, that variable will go out of scope once the function returns and any pointers to it become invalid. For the second type there is no such problem, as the memory pointed to will not go out of scope and will be valid until you free
the memory.
To illustrate with an example:
double *function1(void)
{
double array[SOME_SIZE];
return array;
}
double *function2(void)
{
double *ptr = malloc(SOME_SIZE * sizeof(*array));
return ptr;
}
int main(void)
{
double *ptr1 = function1(); // Invalid pointer
double *ptr2 = function2(); // Okay pointer
}
The function1
function will return a pointer to the local variable array
, but as soon as the function returns array
goes out of scope, so in main
the variable ptr1
will not point to valid memory, using that variable in any way except making it point somewhere else leads to undefined behavior.
However function2
return a pointer to dynamically allocated memory that exists for the life-time of the program (or until you call free
using the pointer), and so that pointer will be valid and can be used freely.