楽しいので、私は素数を使ってイメージを作成するプログラムを書いています。このために、ある点までのすべての自然数の2次元配列を作成します。
プライムは画像内で黒のピクセルとして表され、合成番号は白です。 プログラムは1000 * 1000未満のディメンションで動作しますが、それを超えるとスタックされます。 どうすれば修正できますか?何か助けていただければ幸いです。大きい2D配列を定義しづらい - C++
#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;
}
「これは止まってしまいます」それはどういう意味ですか?具体的には – Rakete1111
2つの問題があります。まず、C++には[可変長配列](https://en.wikipedia.org/wiki/Variable-length_array)、2番目にスタックサイズ(配列を含むローカル変数)コンパイラによって格納されているものは非常に限られています。 Windowsのデフォルトのスタック側はプロセスごとに1MBです。スタックに8MBのアレイを作成しようとしています。 –
可能な解決策として、代わりに['std :: vector'](http://en.cppreference.com/w/cpp/container/vector)について学ぶことをお勧めします。 –