开发者

C++: TwoDimensional Array: One dimension fixed?

开发者 https://www.devze.com 2023-01-11 02:50 出处:网络
I need to pass a开发者_如何学C double [][6] to a method. But I don\'t know how to create that two-dimensional array.

I need to pass a开发者_如何学C double [][6] to a method. But I don't know how to create that two-dimensional array.

6 is a fixed size (or a "literal constant", if my terminology is right), which the method accepts. I was trying something like this, but without success...

double *data[6] = new double[6][myVariableSize];

So, the method really looks like:

int myMethod(double obj_data[][6]);

Thanks in advance


I cannot tell from the question which dimension is which, but this might be worth a try:

double (*data)[6] = new double[myVariableSize][6];


In C++ you could use std::array<std::vector<double>, 6>.

typedef std::array<std::vector<double>, 6> my_array_t;

int myMethod( const my_array_t& obj_data );

If your compiler still doesn't support std::array you could use boost::array instead.


This should work:

int myMethod(double obj_data[][6])
...
int myVariableSize = 10;
double (*data)[6] = new double[myVariableSize][6];
myMethod(data);

As mentioned only the first dimension can be variable!


Your method definition should look like this (to match your definition):

int myMethod(double obj_data[6][]);

..but that's not valid C++ because only the first dimension can be undefined. Try the following:

int myMethod(double **obj_data, const int numOfColumns, int numOfRows)
{
    // Set the element in the last column / row to 5
    obj_data[numOfRows-1][numOfColumns-1] = 5;

    return 0;
}


int main(int argc, char* argv[])
{
    // Define array size
    int myNumOfRows = 5;
    const int numOfColumns = 6;

    // Allocate memory
    double** data = new double*[myNumOfRows];
    for (int i = 0; i < myNumOfRows; ++i)
    {
        data[i] = new double[numOfColumns];
    }

    // Do something with the array
    myMethod(data, numOfColumns, myNumOfRows);

    return 0;
}


My colleague and I could get no variations of the problem you proposed to work. But this does work and does compile:

int myMethod(double** obj_data)
{
    return 5;
}

int _tmain(int argc, _TCHAR* argv[])
{
    const int myVariableSize = 3;
    double** b = new double*[3];
    for (int i = 0 ; i < 3;i++)
    {
        b[i] = new double[myVariableSize];
    }

    myMethod(data);

    return 0;
}

I propose you just go back to using a double vector for a 2D array, or use some of Boost's (so I'm told) multi-dimensional arrays.

0

精彩评论

暂无评论...
验证码 换一张
取 消