A function can return a 2d array?Can one some give a explanation of this with example?
I tried the following code but does not work...
Code:int function (array [] [120])
(
/ / program
return array [] [120];
)
Printable View
A function can return a 2d array?Can one some give a explanation of this with example?
I tried the following code but does not work...
Code:int function (array [] [120])
(
/ / program
return array [] [120];
)
Is it possible in C++ to have a function that returns a 2-D or indeed an X-D array from a function.Another alternative is to pass in the 2D array as a parameter into the function (by reference) and then filll it and then just leave the function which would maintain the array's content.
Return a 2D array from a function in C :
Code:#include
struct array_def
{
int **q;
int row1;
int col;
};
int** func();
array_def* func_struc();
void main()
{
int **b = func();
for(int j=0;j < 2; ++j)
{
for(int k=0;k < 2; ++k)
cout<cout<}
array_def *pArr = func_struc();
for(j =0; j < pArr->row; ++j)
{
for(int k =0; k< pArr->cols; ++k)
cout<p[j][k]<cout<}
}
int** func()
{
int **q;
int cnt =7;
q = new int*[2];
for(int j =0;j < 2; ++j)
p[i] = new int[2];
for(j =0; j < 2; ++j)
for(int k=0; k < 2; ++k)
p[j][k] = cnt++;
return q;
}
array_def* func_struc()
{
array_def *pArray = new array_def;
int cnt =1;
pArray->q = new int*[2];
for(int j =0;j < 2; ++j)
pArray->p[j] = new int[2];
for(j =0; j < 2; ++j)
for(int k=0; k < 2; ++k)
pArray->p[j][k] = cnt++;
pArray->cols =2;
pArray->row = 2;
return pArray;
}
In your case you pass an array argument (but bad because you did not indicate the type), this table will be modified directly, so it is unnecessary to return.
A dynamically allocated 2D array can be returned by cons because it is a pointer to pointer.