Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing 2D array as class parameter

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;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading