This has bothered me for a while. A lot of times I find myself making a large buffer to hold a \"maximum\" amount of data. This helps me avoid dynamically allocating and dea
The reason the cast does not work is you are essentially trying to convert a 2 dimensional array to a pointer to an array of pointers that each point to an array of characters.
On option is to create a couple of adapter classes that allow you to access the data as if it were an actual two dimensional array. This will simplify access to both extents of the array and can be extended for usage with the standard library.
#include
#include
#include
template
class MDArray
{
public:
struct SDArray
{
SDArray(Type* data, size_t size) : data_(data), size_(size) {}
SDArray(const SDArray& o) : data_(o.data), size_(o.size_) {}
size_t size() const { return size_; };
Type& operator[](size_t index)
{
if(index >= size_)
throw std::out_of_range("Index out of range");
return data_[index];
}
Type operator[](size_t index) const
{
if(index >= size_)
throw std::out_of_range("Index out of range");
return data_[index];
}
private:
SDArray& operator=(const SDArray&);
Type* const data_;
const size_t size_;
};
MDArray(const Type *data, size_t size, size_t dimX, size_t dimY)
: dimX_(dimX), dimY_(dimY)
{
if(dimX * dimY > DataSize)
throw std::invalid_argument("array dimensions greater than data size");
if(dimX * dimY != size)
throw std::invalid_argument("data size mismatch");
initdata(data, size);
}
size_t size() const { return dimX_; };
size_t sizeX() const { return dimX_; };
size_t sizeY() const { return dimY_; };
SDArray operator[](const size_t &index)
{
if(index >= dimY_)
throw std::out_of_range("Index out of range");
return SDArray(data_ + (dimY_ * index), dimX_);
}
const SDArray operator[](const size_t &index) const
{
if(index >= dimY_)
throw std::out_of_range("Index out of range");
return SDArray(data_ + (dimY_ * index), dimX_);
}
private:
void initdata(const Type* data, size_t size)
{
std::copy(data, data + size, data_);
}
MDArray(const MDArray&);
MDArray operator=(const MDArray&);
Type data_[DataSize];
const size_t dimX_;
const size_t dimY_;
};
int main()
{
char data[] = "123456789";
MDArray md(data, 9, 3, 3);
for(size_t y = 0; y < md.sizeY(); y++)
{
for(size_t x = 0; x < md.sizeX(); x++)
{
std::cout << " " << md[y][x];
}
std::cout << std::endl;
}
std::cout << "-------" << std::endl;
for(size_t y = 0; y < md.size(); y++)
{
const auto& sd = md[y];
for(size_t x = 0; x < sd.size(); x++)
{
std::cout << " " << sd[x];
}
std::cout << std::endl;
}
std::cout << "-------" << std::endl;
for(size_t y = 0; y < md.size(); y++)
{
auto sd = md[y];
for(size_t x = 0; x < sd.size(); x++)
{
std::cout << " " << sd[x];
}
std::cout << std::endl;
}
}