首页 > 解决方案 > 有人可以告诉我我的代码有什么问题吗?

问题描述

我想通过向数组添加值并打印它们来操作指向结构数组的指针。这是代码:

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

}

我收到此错误消息:

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

我究竟做错了什么?

标签: c++pointersbad-alloc

解决方案


简单的错误。在它们具有任何值之前,您使用了nrowsandncols变量。显然,您应该只在给变量赋值后才使用它。

像这样更改您的代码

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

推荐阅读