- 2074 Chaitra · 4 marks
Can a function return an array
Short answer
A function cannot return a whole array, but can return a pointer to the first element. That pointer must address memory that outlives the function, such as a static array or dynamically allocated memory. Returning a local array’s address is invalid.
Can a function return an array to the calling function? Explain with example.
No. A C function cannot return a whole array by value, because an array name is not an assignable value and the return type cannot be an array type. However, it can return a pointer to the first element of an array, and the caller then uses that pointer like an array.
Important rule: the returned pointer must point to memory that still exists after the function ends. A normal local array is destroyed when the function returns, so it must not be returned. Safe choices:
- A
staticarray inside the function. - An array allocated with
malloc(). - An array passed in by the caller (the function fills it).
- An array inside a structure, since a structure can be returned by value.
Example (static array)
#include <stdio.h>
int *makeSquares(void)
{
static int sq[5]; /* static: lives after the function ends */
for (int i = 0; i < 5; i++)
sq[i] = (i + 1) * (i + 1);
return sq; /* returns address of first element */
}
int main(void)
{
int *p = makeSquares();
for (int i = 0; i < 5; i++)
printf("%d ", p[i]);
printf("\n");
return 0;
}
Output:
1 4 9 16 25
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Function returning largest of array · Computer Programming, chapter 7
- Sort array using a function · Computer Programming, chapter 7
- Reverse array and display via pointer · Computer Programming, chapter 9
- Pass array; largest and smallest · Computer Programming, chapter 7
- Pass array; transpose 3×3 matrix · Computer Programming, chapter 7
- Pass student array; display passed students · Computer Programming, chapter 7
- Function template: sum and average of array · Object Oriented Programming, chapter 9
- LandMeasure class and sum function · Object Oriented Programming, chapter 4
- Function template power(base, exp) · Object Oriented Programming, chapter 9