C Programming: Can I Return an Array (from a function)?

You cannot return an array from the function. The code is like:  int[] myFunction();

Instead, the pointer can return to the array’s first element. There are also several elements to read.

/* here the name of the function indicate that 5 elements will be returned */
int* getMyTop5()
return &(myTop5[0]);

If you work on these codes, it is necessary to include mechanisms about the array length’s return. If you get int*, you will not identify the array length. If it is array versus a single int, you cannot safely construe it. You can check programming questions and answers and find any programming solutions you need with our help.

The most common and natural way to do that is to have the function’s out parameter. This provides information about the names, comments and array sizes. For an instance:

/* out_arraySize must be a valid address */
int* myFunction(int* out_arraySize)
int* myArray = (int*)malloc(5, sizeof(int));
*out_arraySize = 5;
return &(myArray[0]);

You can use the above function or you do can do something similar to this:

nt arrayCount = 0;
int* arrayContent = myFunction(&arrayCount);

if (arrayContent != NULL)
for (int i = 0; i < arrayCount; ++i)
printf(“%i\n”, arrayContent[i]; /* or whatever you want */