c++ - 有人可以告诉我我的代码有什么问题吗?
问题描述
我想通过向数组添加值并打印它们来操作指向结构数组的指针。这是代码:
#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
andncols
变量。显然,您应该只在给变量赋值后才使用它。
像这样更改您的代码
cout << "Insert ncols : ";
cin >> ncols;
cout << "Insert nrows : ";
cin >> nrows;
data = new words [ncols * nrows];
推荐阅读
- antlr4 - 如何在 9 - 9 的算术运算中编写区分 -9 和 - 运算符的词法分析器规则?
- r - 尝试使用 WOE 包为 r 中的多列使用 for 循环创建 bin,我如何使用 for 循环中的列名来创建多个结果
- java - 在使用属性文件配置的项目中使用 slf4j 将 log4j 升级到 log4j2
- php - laravel 5.7 中的 PostTooLargeException
- office365 - 这是一种按“修改日期”过滤 O365 内容搜索结果的方法吗?
- r - 按组为 FALSE 和 NA 之间的 TRUE 运行创建计数器
- python - 无法识别人脸时如何触发警告?
- apache-kafka - Flume HDFS sink with Kafka source - 多个文件?
- javascript - 在确认对话框上单击“确定”后如何停止功能?
- python - Django JSONField 不保存 0 值