I am trying to create a simple function that takes an int arg and returns a pointer to an int[5] array.
The array and function definition are defined as follows and compile correctly.
However, the code to invoke the function and receive the returned array, won't compile.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int ia[5] = {10, 20, 30, 40, 50}; /// array
int (* f3a (int)) [5] /// function
{
return &ia;
}
int main()
{
int* iar1 = f3a(1);
return 0;
}
This gives the following compilation error:
error: invalid conversion from 'int (*)[5]' to 'int*' [-fpermissive]|
To solve this problem, I need to define the function differently - to return an int pointer, and then the function code returns the array. Then, invocation is perfectly OK.
The question is : How can the first technique to define a function that returns an array, be made to work? It is based on an example given by Bruce Eckel in TICPP. Hence the query.
Thanks for the replies. I shall study them in detail.
TICPP stands for "Thinking in C++", the free e-book written by Bruce Eckel, who is also famous for his book TIJ ("Thinking in Java"). Both e-books are freely downloadable from Bruce Eckel's website www.bruceeckel.com.
Yes, The following code is working and thanks very much for the same:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int ia[5] = {10, 20, 30, 40, 50}; /// array
int (* f3a (int)) [5] /// function
{
return &ia;
}
int main()
{
/// Invoke the function directly.
int (*iar1) [5] = f3a(1); /// WORKS PERFECTLY
print(*iar1);
return 0;
}
However, I have also tried defining a pointer to the above function. That works's fine, but when I try invoking the function through the pointer, the program crashes:
1 2 3 4
int (* (*fp3a) (int)) [5]; /// function pointer
/// Invoke the function through the pointer.
int (*iar2) [5] = (*fp3a) (1); /// PROGRAM CRASHES AT THIS LINE
Yes, you are quite right. Actually, I had forgotten to initialize the function pointer to the function's address, and was trying the dereference the pointer though it was uninitialized.
#include <iostream>
#include <exception>
int ia[5] = {10, 20, 30, 40, 50}; /// array
int (* f3a (int)) [5] /// function
{
return &ia;
}
int (* (*fp3a) (int)) [5] = f3a; /// function pointer
/// Helper function to print an array.
void print(int ia[])
{
for(int i = 0; i < 5; i++)
cout << ia[i] << " ";
cout << endl;
}
/** Arrays to store Function return values
Each variable is a pointer to an int[5] array.
This is necessary since the function returns
a pointer to an int[5] array.
*/
int (*iar1) [5];
int (*iar2) [5];
int main()
{
/// Invoke the function directly.
iar1 = f3a(1);
print(*iar1);
/// Invoke the function through the pointer.
iar2 = (*fp3a)(1);
print(*iar2);
return 0;
}