我想通过向数组添加值并打印它们来操作指向结构数组的指针。这是代码:
#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
我做错了什么?
简单的错误。在
像这样更改代码
cout << "Insert ncols : ";
cin >> ncols;
cout << "Insert nrows : ";
cin >> nrows;
data = new words [ncols * nrows];
int ncols, nrows;
words* data;
data = new words [ncols * nrows];
这是未定义的行为。您的
cout << "Insert ncols : ";
cin >> ncols;
cout << "Insert nrows : ";
cin >> nrows;
这确实会初始化它们,但是您是在创建
要修复您的问题,首先初始化您的变量,然后使用它们。