0
How can i retun a 2d array?
i define a function that produce a 2d array but i can't retun this array to int main :-(
7 Réponses
+ 5
c++ does not allow to return an multiple data as return to a function. However, you can return a pointer to an array by specifying the array's name without an index.
You can also use static keyword. If an array is static it can return as an array but it should store in pointer which will be array data type.
+ 4
here it is
#include <iostream>
using namespace std;
int *add5toeach(int n, int z)
{
static int arr[2];
arr[0]=n+5;
arr[1]=z+5;
return arr;
}
int main() {
int x,y,*a;
x=5;
y=8;
a= add5toeach(x,y);
for(int i=0;i<2;i++)
{
cout << a[i];
cout << " ";
}
return 0;
}
Remember I am returning a address of a variable to pointer thatswhy I have use int *function_name. Also c++ does not support to send address of local variable. You have to use static keyword. Hope you understand
+ 3
For 2d array take a look at this
http://stackoverflow.com/questions/8617683/return-a-2d-array-from-a-function
for vector
http://stackoverflow.com/questions/22655059/why-it-is-ok-to-return-vector-from-function
0
aditya would you give example for better understanding?
0
this example work for vectors
can you give an example for matix(2darray)?
0
👍
0
you can return 2 or more data . but it is complicated
I will show you an example
int func (int x,int *b,int *c)
{
*b=x/2;
*c=x*x+1;
return x +6;
}
// it's an example
int main ()
{
int a,b,c,d;
cin>>a;
d=func (a,&b,&c);
}
and this is how you can return multiple information with cpp