无法初始化 512x512 阵列
unable to initialize a 512x512 array
嘿,我只想说为什么每当我尝试初始化 512x512 数组时总是出现堆栈溢出错误?谁能帮忙?下面是我代码的一部分
CImg<float> image("lena8bit.jpg");
CImgDisplay main_disp(image,"Main image");
int ImgArray [512][512];
基本上我想做的是从图像中获取像素值并将其存储到这个数组中。图像为 512x512,因此数组大小。
希望听到您的回答,谢谢!
您的数组太大,无法在堆栈上分配。
您必须在堆上分配它,并new[]
(并使用delete[]
进行释放)。
因此,您可以像这样创建数组:
// Create the array
int ** myArray = new int*[512];
for(int i=0; i<512; i++)
myArray[i] = new int [512];
myArray[12][64] = 52; // Work with the array as you like
// Destroy the array
for(int i = 0 ; i < 512 ; i++ )
delete [] myArray[i];
delete [] myArray;
其他答案显示了可以为不在堆栈上的二维数组中的图像分配内存的方法,但通常在处理图像时,最好使用一维数组并直接索引到该数组中,例如:
const int width=512, height=512;
std::vector<int> pixels(height*width);
然后,您可以在特定坐标处找到像素:
// Find an x and y position:
int x=12, y=12;
int &px = pixels.at((y*width) + x);
或者找到特定像素的坐标:
// Find the x and y values of pixel 100;
int idx = 100;
x = idx % width;
y = idx / width;
这些都是简单的整数运算,通过这样做,您将只需要担心每个图像一个连续的内存块。您可以让类似的东西std::vector
以干净安全的RAII方式为您管理该内存。
我看到两个尚未提及的解决方案。您可以使用具有静态存储持续时间的内存:
static int ImgArray [512][512];
请注意,如果数组声明为 static
,则该数组将在整个程序中存在。如果您计划从不同的线程多次调用该函数,或者该函数是递归的,则这可能是一个问题。
或者,您可以从堆中分配数组,并通过唯一的指针管理生存期:
std::unique_ptr<std::array<std::array<int, 512>, 512>> p
(new std::array<std::array<int, 512>, 512>);
如果你写一个小的辅助函数,语法看起来不那么复杂:
auto p = make_unique<std::array<std::array<int, 512>, 512>>();
答案取决于您使用的平台。例如Microsoft Visual Studio默认使用1MB的堆栈大小。您可以通过以下方式更改应用程序的默认堆栈大小 使用/STACK 链接器选项。
在 Linux 上它有点不同,可能这可能会对您有所帮助。
但是我认为使用动态内存分配更适合您的情况。
ImgArray** arr = new ImgArray* [512];
for(int i =0; i< 512; i++) arr[i] = new ImgArray[512];
通常,在 32 位操作系统中,每个线程的堆栈具有默认大小 4K。
所以你的阵列比它大。你可以做到
-
将数组定义为未在堆栈中分配的全局变量或静态变量。
-
使用 new/malloc 在堆上分配
- OpenMP阵列性能较差
- 如何将三维尺寸不固定的三维阵列展平为一维阵列
- 当我的阵列太大时出现分段错误
- 位阵列上的快速AND运算
- 阵列必须使用大括号封闭的初始器进行初始化
- 没有从阵列<float>到阵列<int>的可行转换
- C++动态安全 2D 交错阵列
- 将平面阵列重塑为复杂的特征类型
- 如何使用英特尔 PIN 捕获阵列的所有负载?
- 为什么我能够为阵列分配比计算机实际拥有的内存更多的内存
- 库特<<恩德尔;不适用于打印 2D 阵列
- 数组类 阵列的打印输出
- 从较小的阵列到较大的阵列的元素级转换
- 仅在大型阵列上出现合并排序分段错误
- 从阵列C++中删除重复项
- 阵列的大小在C++中是否灵活?
- 反转阵列中的正序列
- 具有可变尺寸的 C++ 2D 阵列
- 二维阵列的动态分配
- 无法初始化 512x512 阵列