简体   繁体   中英

C++ dynamic 2D array

I am using the following code to create dynamic 2D array.

uint32_t** arrays = new uint32_t*[10]; 
uint32_t number = take input from console ;
arrays[0] = new uint32_t[number];
number = take input from console ;
arrays[1] = new uint32_t[number];
delete arrays[0] ;
number = take input from console ;
arrays[0] = new uint32_t[number] ;

Can any one help me how to know the size of the 2nd dimension without knowing the input values ? Means how to find the array size on arrays[0], arrays[1] and so on ?

There is no way to determine the size of a memory block allocated by new without storing the size value.

EDIT: also, why not just use a vector< vector< uint32_t > > arrays; ?

std::vector<std::valarray<uint32_t> > may also be an alternative. Assuming, that your console program will do some sort of calculation, the rather unknown std::valarray will be a good companion.

Be aware of the risk, that user provided size values are likely to lead to a std::bad_alloc exception, so you may put at least the allocations into a try/catch block.

Another solution would be to collect all user provided size values in a container and then instantiate another, single container for data:

//Disclaimer: below code has never been tested and is rather about how to do such stuff in general,
//regardless of the few bytes gained for sacrificing CPU cycles.

#include <vector>
#include <valarray>
#include <numeric>
#include <cassert>
#include <exception>

void app(void)
{
    std::vector<size_t> sizes;
    std::valarray<uint32_t> data;

    try
    {
        //collect N user defined sub-vector size values in 'sizes'
        //.
        //.
        //.
        size_t totalNumberOfValues = std::accumulate(sizes.begin(),sizes.end(),0u);
        data.resize(totalNumberOfValues);
    }
    catch(std::bad_alloc& e)
    {
        //handle error
    }

    //accessing the minor/sub-vectors using the size values requires accumulation of adjacent size values of preceding sub-vectors.    
    //of course, these offsets could also be pre-computed.

    size_t subVectorIndex /*...*/; //needs to be checked!
    assert(subVectorIndex < sizes.size());

    size_t subVectorSize = sizes[subVectorIndex];
    size_t subVectorOffset = std::accumulate(sizes.begin(),sizes.begin()+subVectorIndex,0u);

    //do NOT reallocate 'data' while twiddling around with pointers!
    uint32_t* subVectorData = &data[subVectorOffset];

    //well, using neat stuff like std::slice, std::gslice etc. is up to you now ;-)
}

There is no way to do that. For the sake of memory efficiency the size of the allocated memory block is not guaranteed to be stored anywhere. Consider using vectors instead of plain arrays for the 2nd dimension.

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