Return a local 2d Array
-
In the following code, I tried to return a 2D local array from the getArray function and display it in the main function. I use the following line to display the matrix
cout << " " << *(*(ptr+i*COL)+j)
but it is not displayed. Does anyone know how to display the array?
#include
#define ROW 3
#define COL 4
using namespace std;int main()
{
int **ptr;
int **getArray();ptr = getArray(); cout << "\\n Array tab\[\]\[\] in main(): " << endl << endl; for (int i=0; i
-
In the following code, I tried to return a 2D local array from the getArray function and display it in the main function. I use the following line to display the matrix
cout << " " << *(*(ptr+i*COL)+j)
but it is not displayed. Does anyone know how to display the array?
#include
#define ROW 3
#define COL 4
using namespace std;int main()
{
int **ptr;
int **getArray();ptr = getArray(); cout << "\\n Array tab\[\]\[\] in main(): " << endl << endl; for (int i=0; i
-
Why this line? cout << " " << (int)*(ptr+i+j) << endl;
Can you give me more details ? Why do you need a type-casting conversion ?
Multidimensional arrays declared the way you have are just an abstraction for programmers, since the same results can be achieved with a simple array, by multiplying its indices: int jimmy [3][5]; // is equivalent to int jimmy [15]; // (3 * 5 = 15) In effect GetArray returns a 1D pointer array and you could have simply returned it as int* as it's really a big 1 dimensional array You returned int** so the typecast is to deal with it but it would have been simpler like this
int *getArray()
{
static int tab[ROW][COL] = {
11, 12, 13, 14,
21, 22, 23, 24,
31, 32, 33, 34,
};
return (int*)tab;
}Then the access becomes more obvious
int *ptr = getArray();
cout << "\n Array tab[][] in main(): " << endl << endl;
for (int i = 0; i
In vino veritas -
Why this line? cout << " " << (int)*(ptr+i+j) << endl;
Can you give me more details ? Why do you need a type-casting conversion ?
-
In the following code, I tried to return a 2D local array from the getArray function and display it in the main function. I use the following line to display the matrix
cout << " " << *(*(ptr+i*COL)+j)
but it is not displayed. Does anyone know how to display the array?
#include
#define ROW 3
#define COL 4
using namespace std;int main()
{
int **ptr;
int **getArray();ptr = getArray(); cout << "\\n Array tab\[\]\[\] in main(): " << endl << endl; for (int i=0; i
The return type for
getArray
needs to beint (*getArray())[COL];
. An expression of typeT [M][N]
decays to typeT (*)[N]
, notT **
. So your code needs to beint main()
{
int (*ptr)[N];
int (*getArray())[N];
...
}int (*getArray())[N]
{
...
return tab;
}