passing Multidimensional Array to a function!

Hi every one
i learned how to pass one dimensional array to a function, i did the same way with two dimensions but i failed .
can any one help me with this issue?
Many thanks

How are you tryiong to pass it?
Show an example.
Thats the only way i now about:
void printarr(int m[], int l);

int main(){
int m[5]={1,2,3,4,5};

printarr(m,5);


}

void printarr(int x[],int l){
for (int i=0;i<l;i++){
cout << x[i] << " ";

}
}
That is one dimensional array. I asked about
i did the same way with two dimensions but i failed
Just what you did?

Either way, there is several flavors of multidimensional arrays. They works differently and uncompatible with each other.

Taking basic automatic storage array:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

void print(int arr[][5], int width)
{
    for (int i = 0; i < width; ++i) {
        for(int j = 0; j < 5; ++j)
            std::cout << arr[i][j] << ' ';
        std::cout << '\n';
    }
}

int main()
{
    int array[2][5] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 0}};
    print(array, 2);
}
Last edited on
yes iam sorry i thought you meant the way for passing one dimensional array, i did it this way but i failed , i know the way you show me works fine i run your code, but in case i want to pass the two dimensions to the function i failed to do it correctly ..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void print(int arr[][], int width,int h)
{
    for (int i = 0; i < width; ++i) {
        for(int j = 0; j < h; ++j)
            std::cout << arr[i][j] << ' ';
        std::cout << '\n';
    }
}

int main()
{
    int array[2][5] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 0}};
    print(array, 2 ,5);
}
When passing multidimension arrays, all dimensions aside from first should be known beforehand.

Here is an article describing different approaches to multidimensional arrays, how they can create problems and some solutions: http://www.cplusplus.com/forum/articles/17108/
Last edited on
Like MIINI said

1
2
3
4
void print(int arr[][], int width,int h)//error

void print(int arr[][5], int width,int h)//correct
//you have to know the dimensions  
Many thanks , i have better understanding about the MD Arrays and passing them to functions .
Topic archived. No new replies allowed.