【发布时间】:2019-08-06 08:50:08
【问题描述】:
#include <iostream>
char** make2D(const int dim1, const int dim2)
{
char* toAlloc;
const int size = (dim1 * dim2) + dim2;
toAlloc = new char[size];
for(int i = 0; i < dim2; i++)
{
toAlloc[i] = reinterpret_cast<char>(&toAlloc[(dim2 + (dim1 * i))]);
}
return reinterpret_cast<char**>(toAlloc);
}
int main(void)
{
int dim1 = 8;
int dim2 = 10;
char** array2D = make2D(dim1, dim2);
for (int i = 0; i < dim2; ++i)
{
array2D[i][i % dim1] = i + 100; // << Crash
}
return 0;
}
我试图通过一次分配来分配二维数组。
因此,我的算法是,前 10 个(在此代码中为 dim2)项具有指向每行第一项的指针。
当我通过指向'int'的指针尝试这个时,
int** make2D(const int dim1, const int dim2)
{
int* toAlloc;
const int size = (dim1 * dim2) + dim2;
toAlloc = new int[size];
for(int i = 0; i < dim2; i++)
{
toAlloc[i] = reinterpret_cast<int>(&toAlloc[(dim2 + (dim1 * i))]);
}
return reinterpret_cast<int**>(toAlloc);
}
int main(void)
{
int dim1 = 8;
int dim2 = 10;
int** array2D = make2D(dim1, dim2);
for (int i = 0; i < dim2; ++i)
{
array2D[i][i % dim1] = i + 100;
}
return 0;
}
它工作正常,但是当我在 char 中执行此操作时,它会在上面代码的注释行中崩溃。
我想到崩溃是当我执行reinterpret_cast 时,由于指针(8 字节)和字符(1 字节)之间的内存大小差距而发生了一些事情。
就像,听起来很荒谬......将指针(8byte)更改为int(4byte)很好,但是当我更大幅度地转换(8byte到1byte)时,它会导致一些问题......
我不知道为什么 char 不起作用但 int 起作用。 您能给 char case 提供一些建议吗?
【问题讨论】:
-
那个代码错的地方太多了。
char通常是 8 位,一个字节。在 32 位平台上,指针通常为 32 位。您如何能够将 32 位数据放入 8 位值中?而在 64 位系统上,指针通常是 64 位,是char大小的八倍。 -
更不用说
toAlloc不是一个指针数组,这样使用它是错误的(不管它是否起作用)。 -
reinterpret_cast是一个危险信号。在您认为需要reinterpret_cast的 99% 的情况下,您做错了什么 -
将
std::vector或std::array用于动态/固定大小的数组,并围绕2 个或更多维度包装一些索引映射。其他任何事情都不必要地复杂
标签: c++ memory-management allocation reinterpret-cast