If this is possible:
#include <stdio.h>
#include <process.h>
#define SIZE 5
void PassingArray(int arr[])
{
int i=0;
for(i=0 ; i<SIZE ; i++)
{
printf("%d, ", arr[i]);
}
printf("\n");
}
main()
{
int myIntArray[5] = {1, 2, 3, 4, 5};
PassingArray(myIntArray);
system("PAUSE");
}
Then why the following is illegal?
#include <stdio.h>
#include <process.h>
#define SIZE 5
int ReturningArray()[]
{
int myIntArray[5] = {1, 2, 3, 4, 5};
return myIntArray;
}
main()
{
int myArray[] = ReturningArray();
system("PAUSE");
}
There’s multiple reasons why this doesn’t work.
The first is simply that it’s prohibited by the language – the return type of a function shall not be an array (it also can’t be a function).
The second is that even if you were allowed to declare
ReturningArrayas you do, you could never write a validreturnstatement in that function – an expression with array type that is not the subject of the unary&orsizeofoperators evaluates to a pointer to the first element of the array, which no longer has array type. So you can’t actually makereturnsee an array.Thirdly, even if we somehow had a function returning an array type, you couldn’t use that return value as the initialiser of an array variable – the return value would again evaluate to a pointer to the first element of the array: in this case a pointer to
int, and a pointer tointisn’t a suitable initialiser for an array ofint.