Home > database >  Passing 2D array as class parameter
Passing 2D array as class parameter

Time:05-27

I am trying to set up a class that initializes with a 2d array of an unknown size at compile time. I figured the best way to do this would be to pass the array as a pointer. This works as expected with a 1d array, but when I try to do the same with a 2d array. I get an error that states that it cannot convert argument 2 from 'char [3][3]' to 'char*'. Does anyone have a simple explanation on how I can get this to work? Here is my code.

TestClass.h:
#pragma once
#include <iostream>

class TestClass
{
public:

    std::string name;
    char *data;
    TestClass(std::string name, char *data);
};
TestClass.cpp:
#include "TestClass.h"

TestClass::TestClass(std::string name, char *data)
{
    this->name = name;
    this->data = data;
}
Main.cpp:
#include "TestClass.h"

int main()
{
    char TestArray[3][3] = {{ 'A', 'B', 'C' },
                            { 'D', 'E', 'F' },
                            { 'G', 'H', 'I' }};

    TestClass Test("TestName", TestArray);
    std::cout << Test.data[2] << std::endl;

    return 1;
}

CodePudding user response:

You can pass a 2D array by passing the address of the first element:

TestClass Test("TestName", &TestArray[0][0]);

But how is TestClass supposed to know the dimensions of the array? There is no way to query the data or to guess. You have to also pass num_rows and num_cols.

But then I see:

std::cout << Test.data[2] << std::endl;

So now you want the 2D array to be a 1D array of C-style strings? That's is not what your data represents.

You really should forget about all the C-style cruft and use modern C construct. Use std::vector<std::string> to store a variable number of strings.

CodePudding user response:

The problem is that the constructor's second parameter is of type char* but you're passing a 2D array TestArray which will decay to char (*)[3] and since there is no implicit conversion from char(*)[3] to char* you get the mentioned error.

To solve this you can either make the second parameter of the constructor to be a pointer to an array of size 3(but then you'll also have to change the type of data) or better yet use std::vector and std::string.

  • Related