我想通过将值添加到数组并打印它们来操纵结构数组的指针。这是代码:
#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
我究竟做错了什么?
简单错误。在nrows
和ncols
变量具有任何值之前,请使用它们。显然,只应在给变量赋值后使用它。
像这样更改您的代码
cout << "Insert ncols : ";
cin >> ncols;
cout << "Insert nrows : ";
cin >> nrows;
data = new words [ncols * nrows];
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句