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

  arrayofstruct, bad-alloc, c++, pointers

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?

Source: Windows Questions C++

LEAVE A COMMENT