微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

有人可以告诉我我的代码有什么问题吗?

如何解决有人可以告诉我我的代码有什么问题吗?

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

#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

我做错了什么?

解决方法

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

像这样改变你的代码

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];

这是未定义的行为。您的 ncolsnrows 未初始化。稍后你会这样做:

cout << "Insert ncols : ";
cin >> ncols;
cout << "Insert nrows : ";
cin >> nrows;

哪个初始化它们,但是你在创建data数组之后这样做。在 ncols 行之后修改 nrowsnew words [ncols * nrows] 不会改变该数组的大小。这些值不受约束。它们用于创建数组。一次性工作。

要解决您的问题,请先初始化您的变量,然后再使用它们。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。