Hello. I want to use my multidimensional array of pointers on a function, but i don't know how to pass this array to the function.
I want this code to work, but no way to do it :(
#include <iostream>
#include <string>
usingnamespace std;
void function (int *Array[][]);
int main()
{
int *array[2][2];
for (int i=0; i<3; i++){
for (int j=0; j<3; j++){
*array [i][j]=0;
}
}
function (&array);
for (int i=0; i<3; i++){
for (int j=0; j<3; j++){
cout << *array [i][j]=0;
}
}
}
void function (int *Array[][]){
for (int i=0; i<3;i++){
for (int j=0; j<3; j++){
*Array [i][j]=1;
}
}
}
Some compile errors:
6: declaration of 'Array' as multidimensional array must have bounds for all dimensions except the first
19: no match for 'operator=' (operand types are 'std::basic_ostream<char>' and 'int')
23: same as 6
26:'Array' was not declared in this scope
I'm not sure exactly what your program is intended to do, as it contains a number of errors. When passing an array to a function, all dimensions but the first must be explicitly stated (or state all of them). In the for loops, you are accessing elements 0, 1 and 2 (three elements, but the array has only two elements. That's an out of bounds error. A pointer needs to point to something. I'm not sure your code does that.
So here's an example which at least compiles and does something.
#include <iostream>
#include <string>
usingnamespace std;
void function (int *Array[][2]);
int main()
{
int data[4] = {2, 3, 5, 7};
int *array[2][2];
int *n = data;
// make sure the pointers point to an integer
for (int i=0; i<2; i++) {
for (int j=0; j<2; j++) {
array [i][j] = n++;
}
}
for (int i=0; i<4; i++)
cout << data[i] << ' ';
cout << endl;
function (array);
for (int i=0; i<4; i++)
cout << data[i] << ' ';
cout << endl;
return 0;
}
void function (int *Array[][2]) {
int dat2[4] = {19, 17, 13, 11};
int *p = dat2;
// leave the pointers alone, and alter the value which it is pointing to.
for (int i=0; i<2;i++) {
for (int j=0; j<2; j++) {
*Array[i][j] = *p++;
}
}
}