C++ 程序在 Linux 上运行完美,但在 Windows 上无法运行

标签 c++ linux windows g++ codeblocks

我有这段代码可以在 Ubuntu 16.04.3 LTS 上完美运行。但是当我在 Windows 上通过 Codeblock 构建和运行它时。这只是崩溃。我不知道我错了什么,我该如何解决这个问题。我写的很多 C++ 程序可以在 Linux 上运行,但在 Windows 上会崩溃。

Crashed Pricture

非常感谢你们的帮助!

#include <iostream>

using namespace std;

int d = 1;

void topRight(int [999][999], int, int, int, int);
void bottomLeft(int [999][999], int, int, int, int);

void topRight(int a[999][999], int x1, int y1, int x2, int y2) {
  for (int i=x1;i<=x2;i++) a[y1][i]=d++;
  for (int j=y1+1;j<=y2;j++) a[j][x2]=d++;
  if (x2-x1>0 && y2-y1>0){
    y1++;
    x2--;
    bottomLeft(a,x1,y1,x2,y2);
  }
}

void bottomLeft(int a[999][999], int x1, int y1, int x2, int y2) {
    for (int i=x2;i>=x1;i--) a[y2][i]=d++;
    for (int j=y2-1;j>=y1;j--) a[j][x1]=d++;
    if (x2-x1>0 && y2-y1>0) {
        x1++;
    y2--;
        topRight(a,x1,y1,x2,y2);
    }
}

int main(void){
  int a[999][999],m,n,i,j;
  cout << "Insert n: ";
  cin >> n;
  cout << "Insert m: ";
  cin >> m;
  topRight(a,0,0,n-1,m-1);
  cout << "\nA spiral-shaped two-dimensional array whith size " << m << " x " << n << " is: \n\n";
  for(i=0;i<m;i++){
    for(j=0;j<n;j++){
      cout << a[i][j] << "  ";
    }
    cout << "\n";
  }
}

我用这个命令在 Ubuntu 终端上编译:

g++ program.cpp -o program

然后用这个命令运行它:

./program

最佳答案

当你用简单的数学声明 999x999 矩阵时:

999*999 = 998001

一个整数在内存中占4个字节,所以

998001*4 = 3992004

几乎等于 4*10^6 字节。当您在主函数中声明一个变量时,它会尝试从堆栈中获取内存。在堆栈中,您不能提供这样的内存。这就是您收到 stackoverflow 错误的原因。

尝试减小矩阵的大小或将此变量声明为全局变量。但是全局变量也是有限制的。

关于C++ 程序在 Linux 上运行完美,但在 Windows 上无法运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47855589/

相关文章:

c - 在 C 中模拟 shell 命令行

windows - 使用通配符重命名cmd中的文件

c++ - 容器元素自行删除?

c++ - 更新旧版 C makefile 以包含 C++ 源文件

c++ - gcc 警告未使用的 RAII 变量

命令输出(stdout、stderr)未重定向到管道

linux - 使用名称启动进程

c++ - 指向数组声明的指针

windows - 如何从 config.txt 上的 7zip sfx 文件设置在 "RunProgram"之前或之后运行 exe?

c++ - 记录第二个键盘事件