This question has already been answered:

Is it possible in C to make the return type int* func(void) or is it more correct to return an array through a reference in the arguments of the void func(int *mass) function?

 int* f() { int a[2] = {4, 5}; int* p = a; p = (int*)malloc(2 * sizeof(int)); p[0] = a[0]; p[1] = a[1]; return p; } void f(int* p) { int a[2] = {4, 5}; p[0] = a[0]; p[1] = a[1]; //use function malloc in main } 

Reported as a duplicate by participants Harry , VladD , Streletz , sercxjo , D-side 2 Jun '16 at 16:04 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

    1 answer 1

    • If the array size is known in advance, it is safer to create it in the calling code (the second option), since and the allocation and release of memory will be done by one programmer.
    • If the size is not known, it is necessary to return it along with the pointer to the array (otherwise the array is useless), or to do an additional method of returning the required array size (as in WinAPI, for example, the size is returned, if you pass NULL, if you pass a pointer to the array, it is filled + for safety the size of the array created from outside is transferred).
     int f(int *pArray, int nMax) { if (!pArray) return 2; //запрос размера if (nMax < 2) return 0; //ошибка (не достаточно места) int a[2] = {4,5}; pArray[0] = a[0]; pArray[1] = a[1]; return 2; //возвращаем размер } 
    • Thank you) what I was looking for) - John