no return is necessary since an existing array is passed by the address. However, if the function has
created the array on the heap, you can return the address of element 0.
The problem here is that you can't use the function return type unless you a) return a type or
b) return a pointer to a type. That is, you cannot return a pointer to an array since an array is not
a type. So, if you create an array of int you can return the array as an int*:
Expand|Select|Wrap|Line Numbers
- int* func(int arg)
- {
- int* temp = new int[arg];
- return temp;
- }
- int main()
- {
- int* arr = func(5);
- }
Expand|Select|Wrap|Line Numbers
- int (*)[5] func(int arg) // ERROR: Cannot return an array
- {
- int (* temp)[5] = new int[arg][5];
- return temp;
- }
- int main()
- {
- int (* arr)[5] = func(4);
- }
Expand|Select|Wrap|Line Numbers
- void func(int arg, int (**rval)[5])
- {
- int (* temp)[5] = new int[arg][5];
- *rval = temp;
- }
- int main()
- {
- int (* arr)[5] = 0;
- func(4, &arr);
- //arr is now a [4][5] array of int
- }
Expand|Select|Wrap|Line Numbers
- typedef int (*IntArray5Ptr)[5];
Expand|Select|Wrap|Line Numbers
- IntArray5Ptr func(int arg)
- {
- int (* temp)[5] = new int[arg][5];
- return temp;
- }
- int main()
- {
- int (* arrA)[5] = func(4);
- }
Expand|Select|Wrap|Line Numbers
- typedef int IntArray5[5];
- IntArray5* funcB(int arg)
- {
- int (* temp)[5] = new int[arg][5];
- return temp;
- }
- int main()
- {
- int (* arr)[5] = func(4);
- }
Therefore, a function could just create a one-dimensional array of the correct number of elements and return
the address of element 0. In this case, element 0 is a type and you can use the return type of a function
to return a pointer to a type. Then the calling function could typecast the return so the array can be
used with muliple dimensions:
Expand|Select|Wrap|Line Numbers
- int* func(int arg)
- {
- int * temp = new int[arg];
- return temp;
- }
- int main()
- {
- //This is arr[60]
- int* arr = func(60);
- //This is arr[12][5] --> 12 x 5 = 60
- int (*arr1)[5] = (int(*)[5])func(60);
- //This is arr[3][4][5] -> 3 * 4 * 5 = 60
- int (*arr2)[4][5] = (int(*)[4][5])func(60);
- //This is arr[1][3][4][5] -> 1*3*4*5 = 60;
- int (*arr3)[3][4][5] = (int(*)[3][4][5])func(60);
- }
No comments:
Post a Comment