卡在定义大型2d数组-c++中
Stuck defining large 2d-array - c++
为了好玩,我正在编写一个使用素数创建图像的程序。为此,我创建了一个所有自然数到某一点的二维数组
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:如果约阿希姆想转发他的评论作为回答,我建议你接受。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '