我的程序无法正常工作,我的函数不断抛出分段错误

-6 c++ function segmentation-fault

所以我有这个带有函数的代码,它应该将二维数组中的所有数字打印到二次幂,但我的代码不断抛出分段错误,我不知道为什么

#include <bits/stdc++.h>
using namespace std;

void er(int arr[][100000000], int, int);

int main()
{

    int n, m;
    cin >> n >> m;
    int arr[n][100000000];

    er(arr, n, m);

    return 0;
}

void er(int arr[][100000000], int n, int m)
{

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cin >> arr[i][j];
            arr[i][j] *= arr[i][j];
        }
    }
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cout << arr[i][j];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

R S*_*ahu 8

使用

int arr[n][100000000];
Run Code Online (Sandbox Code Playgroud)

在两个帐户上都有问题。

  1. VLA 不是标准的 C++。一些编译器支持它作为扩展。
  2. 100000000堆栈上的变量的大小太大。只要您的编译器支持 VLA ,将其更改为100并确保其m小于或等于100很可能会起作用。

更好的选择是使用std::vector.

int n, m;
cin >> n >> m;
std::vector<std::vector<int>> arr(n, std::vector<int>(m));
Run Code Online (Sandbox Code Playgroud)

当然,这将需要您相应地更改功能er。

此外,请不要使用

#include <bits/stdc++.h>   
Run Code Online (Sandbox Code Playgroud)

请参阅为什么我不应该 #include <bits/stdc++.h>?了解更多详情。