简体   繁体   中英

How to initialiaze a multidimensional dynamically allocated array in a constructor C++?

I have created a class template that holds a union of the following type, which should be of variable length.

union BufferUnion {
    int buf32;
    short buf16[2];
};

class SomeClass {
    
    int nBufs;
    int buflen;

    BufferUnion **bu;

    SomeClass(int nBufs, int buflen);
    ~SomeClass();
}

and now I want to dynamically allocate a few of these buffers in the.cpp file, but I am getting a read violation when trying to call the constructor.

SomeClass::SomeClass(int nBufs, int buflen)
{
    this->nBufs = nBufs;
    this->buflen = buflen;

    for (int i=0; i < nBufs; ++i) {
        bu[i] = new BufferUnion[buflen]; 
    } 
}

First thing you should do when creating the two-dimensional array is to allocate the memory for the first dimension, then iterate on it creating the second dimension. You've got the second part right, but what you're missing is: bu = new BufferUnion*[nBufs] before the loop creating the second dimension.

As a sidenote: What about the comma in for (int i=0; i < nBufs, ++i) instead of semicolon: for (int i=0; i < nBufs; ++i) ? With comma separator the compiler will consider it as only one expression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM