-6

so I have this code that with a function is supposed to take all the numbers in a 2D array and print them to the second power but my code keeps throwing segmentation fault and i don't know why

#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];
        }
    }
}
drescherjm
  • 10,365
  • 5
  • 44
  • 64

1 Answers1

8

Using

int arr[n][100000000];

is problematic on two accounts.

  1. VLAs are not standard C++. It is supported by some compilers as an extension.
  2. The size 100000000 is too large for a variable on the stack. Changing that to 100 and making sure that m is less than or equal to 100 will most likely work as long as your compiler supports VLAs.

A better alternative would be to use std::vector.

int n, m;
cin >> n >> m;
std::vector<std::vector<int>> arr(n, std::vector<int>(m));

Of course, that will require you to change the function er accordingly.

In addition, please don't use

#include <bits/stdc++.h>   

See Why should I not #include <bits/stdc++.h>? for further details.

R Sahu
  • 204,454
  • 14
  • 159
  • 270