Passing an 2D array to function C++

Hello everyone!
I'm new to this forum, so please correct me if I made any mistakes posting my problem.
I've got a following problem which I've tried to solve for hours. I'm trying to pass an 2D char array to a function that would display it on a standard console output.
My first apporach was successful:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
using namespace std;
int DisplayArray(char darray[][4], int x, int y)
{
    int i,j;
    for(i=0;i<=x;i++){
        for(j=0;j<=y;j++){
            cout<<darray[i][j];  //display
        }
    }
    return 0;
}

int main()
{
    const int X=4, Y=4;
    char x='x';
    char o='o';
    char n='\0';

    char default_array[X][Y]={  //array to pass
        {n,n,n,n},
        {n,o,o,n},
        {n,x,x,n},
        {n,n,n,n}};

    DisplayArray(default_array,X,Y); //call
    return 0;
}


This code would display an array without problems. But it only works with pre defined number of collumns(i will add user input for X and Y). Next I tried to declare an array like this:

1
2
3
4
   
    char** default_array = new char*[X];
    for(int i = 0; i < X; ++i)
        default_array[i] = new char[Y];

This time I don't know how to initialise it with the same values as above and how to pass it as pointer to pointer method which I read about on the internet.

Thanks in advance,
Crys
closed account (D80DSL3A)
You can initialize it like a regular 2D array
default_array[i][j] = Aij;// where 0<=i<X and 0<=j<Y

You pass it to a function as the type you declared it as, char**
int DisplayArray(char** darray, int x, int y)

function call:
DisplayArray(default_array, X, Y);
Last edited on
Thank you very much fun2code, I've managed to compile my code without errors/warns now. Then I initialized my default_array like this to make it empty:
1
2
3
for(int i=0;i<X;i++)
        for(int j=0;j<Y;j++)
            default_array[i][j]=n;


n='\0'
Now i can finally pass an array of any range to my display function and output is briliant! :)

Thank you very much!
Crys
I initialized my default_array like this to make it empty

Why didn't you let new[] do it?
default_array[i] = new char[Y](); // allocate and fill with '\0'
also, don't forget a matching nested loop of delete[]s, if you must do this instead of normal containers.
Last edited on
Topic archived. No new replies allowed.