c++pointersbad-alloc

Can someone please tell me what is wrong with my code?


I want to manipulate a pointer to an array of structs by adding values to the array and printing them. This is the code:

#include <iostream>
using namespace std;

struct words {
    char letter;
    bool marked;
};

int main(){
    int ncols, nrows;
    words* data;
    data = new words [ncols * nrows];
    cout << "Insert ncols : ";
    cin >> ncols;
    cout << "Insert nrows : ";
    cin >> nrows;
    data[0].letter = 'a';
    data[1].letter = 'b';
    data[2].letter = 'c';
    data[3].letter = 'd';

    for(int i = 0; i < (ncols*nrows); i++){
        cout << (data+i)->letter << endl;
    }

}

I'm getting this error message:

terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc

What am I doing wrong?


Solution

  • Simple error. You used the nrows andncols variables before they had any value. Obviously you should only use a variable after it has been given a value.

    Change your code like this

    cout << "Insert ncols : ";
    cin >> ncols;
    cout << "Insert nrows : ";
    cin >> nrows;
    data = new words [ncols * nrows];