卡在定义大型2d数组-c++中

Stuck defining large 2d-array - c++

本文关键字:数组 -c++ 2d 大型 定义      更新时间:2023-10-16

为了好玩,我正在编写一个使用素数创建图像的程序。为此,我创建了一个所有自然数到某一点的二维数组

Prime在图像中表示为黑色像素,合成数字为白色。该程序适用于尺寸小于1000*1000的情况,但超过该尺寸时会卡住。我该如何修复它,任何帮助都将不胜感激。

#include <iostream>
#include <cmath>
#include <fstream>
using namespace std;
bool isPrime(long long a){
  if(a==1){return false;}
  if(a==2){return true;}
  if(a%2==0){return false;}
  long long root = sqrt(a);
  for(long long i=3;i<=root;i+=2){
    if(a%i==0){return false;}
  }
  return true;
}
int main(){
  int width = 0, height = 0;
  cout << "Which dimentions do you want the picture to be?" << endl;
  cout << "Width: " << flush;
  cin >> width;
  cout << "Height: " << flush;
  cin >> height;
  /*Create matrix*/
  long long imageMap[height][width];
  long long numberOfPixels = width*height;
  long long i = 1;
  long long x = 0 , y = 0;
  cout << "Number of pixels the image will have: " << numberOfPixels << endl;
  while(i<=numberOfPixels){
    imageMap[x][y] = i;
    x++;
    if(x==width){
      y++;
      x=0;
    }
    i++;
  }
  cout << "Image map done" << endl;
  cout << "Creating prime map, please wait..." << endl;

  /*Generate prime map*/
  int primeMap[width][height]; //The program gets stuck here

  for(long long y = 0; y < width; y++){
    for(long long x = 0; x < height; x++){
      if(isPrime(imageMap[x][y])){
        primeMap[y][x] = 1;
      } else {
        primeMap[y][x] = 0;
      }
      cout << " x = " << x << flush;
    }
    cout << endl << "y = " << y << endl;
  }
  cout << "Writing to file, please wait..." << endl;
  /*Write to file*/
  ofstream primeImage;
  primeImage.open("prime.pbm");
  primeImage << "P1 n";
  primeImage << width << " " << height << "n";
  for(int y = 0; y < width; y++){
    for(int x = 0; x < height; x++){
      primeImage << primeMap[y][x] << " ";
    }
    primeImage << "n";
  }
  primeImage.close();
  cout << "Map creation done" << endl;
  return 0;
}

如果内存可用,应用程序的默认堆栈大小为1MB。约阿希姆是正确的,最好的方法是学习std::vector。但是,如果这只是一个有趣的一次性程序,您可以简单地增加堆栈大小以使其工作。如果您使用的是visualstudio,请打开项目属性并查看链接器系统选项卡。您可以使用堆栈保留值来增加堆栈大小。但我不建议在实际工作项目中这样做。

BTW:如果约阿希姆想转发他的评论作为回答,我建议你接受。