-7

I get a memory error every time I run this. Am I even close?

int **createField(int N, int ** ary) {
    ary = new int*[N];
    for(int i = 0; i < N; ++i)
        ary[i] = new int[N];

    for(int i = 0; i < N; ++i)
        for(int j = 0; j < N+1; ++j)
            ary[i][j] = 0;

    return ary;
}

int playGame (int N, int ** ary) {
    cout<<"Enter the coordinates of the " << N << " shots:"<<endl;
    for(int i = 0; i < N; i++)
    {
        for(int j = 0; j < N; j++)
        {
            cout<<"Enter element ["<<i<<"]["<<j<<"]: ";
            cin>>ary[i][j];
        }
    }
    return 0;
}

int main() {
    int N;
    cout << "Enter the number of Redshirts: ";
    cin >> N;
    int** ary;
    createField(N, ary);
    playGame(N, ary);
 }
Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331

1 Answers1

2

The following don't initialize ary

int** ary;
createField(N, ary);

it should be

int** ary;
ary = createField(N, ary);

but in fact second argument of createField is unneeded, so it would be

int **createField(int N) {
    int** ary = new int*[N];
    for(int i = 0; i < N; ++i)
        ary[i] = new int[N];

    for(int i = 0; i < N; ++i)
        for(int j = 0; j < N+1; ++j)
            ary[i][j] = 0;

    return ary;
}

and then

int** ary = createField(N);

But better would be to use std::vector to not handle memory manually.

Jarod42
  • 203,559
  • 14
  • 181
  • 302