无法初始化 512x512 阵列

unable to initialize a 512x512 array

本文关键字:阵列 512x512 初始化      更新时间:2023-10-16

嘿,我只想说为什么每当我尝试初始化 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。

所以你的阵列比它大。你可以做到

  1. 将数组定义为未在堆栈中分配的全局变量或静态变量。

  2. 使用 new/malloc 在堆上分配