Reputation: 101
I've been trying to pass a multidimensional array, of an unknown size, to a function, and so far have had no luck, when the array is declared, its dimensions are variables:
double a[b][b];
As far as I can tell, I need to give the value of b when I declare the function, a can be unknown. I tried declaring b as a global variable, but it then says that it must be a constant.
ie:
int b;
double myfunction(array[][b])
{
}
int main()
{
int a;
double c;
double myarray[a][b];
c=myfunction(myarray);
return 0;
}
Is there any way get this to work?
Upvotes: 4
Views: 5064
Reputation: 381
if you want to pass an array of unknown size you can declare an array in Heap like this
//Create your pointer
int **p;
//Assign first dimension
p = new int*[N];
//Assign second dimension
for(int i = 0; i < N; i++)
p[i] = new int[M];
than you can declare a function like that:
double myFunc (**array);
Upvotes: 1
Reputation: 5342
Pass by value :
double myfunction(double (*array)[b]) // you still need to tell b
Pass by ref :
double myfunction(int (&myarray)[a][b]); // you still need to tell a and b
Template way :
template<int a, int b> double myfunction(int (&myarray)[a][b]); // auto deduction
Upvotes: 4
Reputation: 1132
Perhaps reading some references on C++ and arrays would help,
http://en.cppreference.com/w/cpp/container/array
Upvotes: 1