C++ Stack Overflow 初始化数组

C++ Stack Overflow initialising array

我在初始化我创建的类型的数组时遇到一些问题。

我创建了"TreeEdge.h"和"TreeNode.h",可以在下面的代码中看到:

#pragma once
#include "TreeEdge.h"

class TreeNode {

TreeEdge northEdge;
TreeEdge eastEdge;
TreeEdge southEdge;
TreeEdge westEdge;
int xCoord;
int yCoord;

public:

// Default constructor
TreeNode() {

}

//constructor 2
TreeNode(int xInput, int yInput) {
    xCoord = xInput;
    yCoord = yInput;
}

void setEastSouthEdges(TreeEdge east, TreeEdge south) {
    eastEdge = east;
    southEdge = south;
}

void setAllTreeEdges(TreeEdge north, TreeEdge east, TreeEdge south, TreeEdge west) {
    northEdge = north;
    eastEdge = east;
    southEdge = south;
    westEdge = west;
}
};

#pragma once


class TreeEdge {

float weight;
int coords[4];

public:

TreeEdge() {

}

TreeEdge(int firstXCoord, int firstYCoord) {
    coords[0] = firstXCoord;
    coords[1] = firstYCoord;
}

void setWeight(float inputWeight) {
    weight = inputWeight;
}

float getWeight() {
    return weight;
}

void setStartCoords(int xCoord, int yCoord) {
    coords[0] = xCoord;
    coords[1] = yCoord;
}

int * getCoords() {
    return coords;
}

void setEndCoords(int xCoord, int yCoord) {
    coords[2] = xCoord;
    coords[3] = yCoord;
}
};

然后我尝试简单地初始化一个 TreeNode 数组,希望用它做一些有用的事情,使用下面的代码...

#include "stdafx.h"
#include <opencv2/opencv.hpp>
#include <stdio.h>

#include "TreeEdge.h" 
#include "TreeNode.h"

using namespace cv;
using namespace std;

int main()
{
// create 2D array for tree
TreeNode imageTreeNodes[544][1024]; // ???????????????? way to use none fixed values

waitKey(0);
return 0;
}

但是,我收到一个错误:“MST.exe 中 0x00007FF6E91493D8 处未处理的异常:0xC00000FD:堆栈溢出(参数:0x0000000000000001、0x0000002BFF003000)。" 程序一进入主函数。

感谢您的帮助。

罗布

您在数组的堆栈上分配了太多内存。

 sizeof(TreeNode); // Returns 88 bytes

因此,在分配 544x1024 元素的二维数组时,您正试图在堆栈上分配 ~49MB!根据 Windows Thread Documentation 进程的默认堆栈大小为 1Mb,因此您遇到的堆栈溢出异常是因为进程 运行 内存不足。

虽然您可以增加进程堆栈大小,但在堆上分配数组可能是更好的主意。这可以使用原始 newdelete 来完成,但也许更好的选择是使用 std::vector。所以改变你的 main() 看起来像:

int main()
{
  std::vector<std::vector<TreeNode>> array(544, std::vector<TreeNode>(1024,TreeNode())) ;
  std::cout << "Array number of rows: " << array.size() << std::endl; // Prints 544
  std::cout << "Array number of columns: " << array[0].size() << std::endl; // Prints 1022
}