【问题标题】:my program wont work properly and my function keeps throwing segmentation fault [closed]我的程序无法正常工作,我的函数不断抛出分段错误 [关闭]
【发布时间】:2020-04-20 07:05:33
【问题描述】:

所以我有这个代码,它应该使用一个函数来获取二维数组中的所有数字并将它们打印到二次方,但是我的代码不断抛出分段错误,我不知道为什么

#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];
        }
    }
}

【问题讨论】:

  • for(int j=0;j&lt;m;i++) 应该是for(int j=0;j&lt;m;j++)
  • 我已经解决了这个问题,但它一直在抛出分段错误
  • 你解决了这两个问题吗? int arr[n][100000000]; 也不是标准 C++,你应该使用 std::vector&lt;std::vector&lt;int&gt;&gt; 来代替
  • int arr[n][100000000] 不是有效的 C++,因为 n 不是编译时常量。
  • #include &lt;bits/stdc++.h&gt; using namespace std; 现在。

标签: c++ function segmentation-fault


【解决方案1】:

使用

int arr[n][100000000];

在两个帐户上都有问题。

  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));

当然,这需要你相应地更改函数er

另外,请不要使用

#include <bits/stdc++.h>   

更多详情请参阅Why should I not #include <bits/stdc++.h>?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-28
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-28
    • 1970-01-01
    相关资源
    最近更新 更多