【问题标题】:Reading Invalid Data读取无效数据
【发布时间】:2021-04-26 03:31:26
【问题描述】:

我在编译程序时收到此警告

从“revval”读取无效数据:可读大小为“revsize*4”字节,但可能读取“8”字节

我的警告列表中出现了太多类似的警告。它大约有6个。但是所有这些看起来都类似于下面的代码。只有变量发生了变化。

这是我整个程序中的一段代码

int revsize = 0;
int* revval;

string revlist[30];
revval = new int[revsize];

system("cls");

cout << "\nHow many revenue do you want to calculate : ";
cin >> revsize;

if (revsize > 0) {
    for (int p = 0; p < revsize; p++) {
        cout << "Enter the name of the expense : ";
        cin >> revlist[p];

        cout << revlist[p] << " : ";
        cin >> revval[p];
        revtotal += revval[p];
    }
}

如何摆脱这个警告?我之前尝试初始化所有变量,但它似乎不起作用。

【问题讨论】:

  • 提示:不要使用 C 数组,使用 std::vector&lt;std::string&gt;。这样可以避免问诸如“有多少?”之类的问题。因为你不在乎,只要继续添加,直到有人输入一个空行或类似的东西。这对于使用new[] 来说是双倍的。除非您完全了解这种方法的后果,否则请避免使用它。请改用std::vector&lt;int&gt;。更好的是,使用 std::stringint 属性制作一个简单的 struct,然后将 那些 添加到您的向量中。

标签: c++ windows


【解决方案1】:

你需要在第一次输入revsize之后分配动态数组,我建议使用vector以避免手动管理内存。使用vector&lt;string&gt; 来避免使用固定大小的数组,这样会更流畅,大小可以大于程序中的30 幻数。

#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
  int revsize = 0;

  std::vector<std::string> revlist;
  int revtotal = 0;

  // system("cls");

  cout << "\nHow many revenue do you want to calculate : ";
  cin >> revsize;
  std::vector<int> revval;

  if (revsize > 0) {
    for (int p = 0; p < revsize; p++) {
      cout << "Enter the name of the expense : ";
      std::string name;
      cin >> name;
      revlist.push_back(std::move(name));

      cout << revlist[p] << " : ";

      int val;
      cin >> val;
      revval.push_back(val);
      revtotal += revval[p];
    }
  }
  std::cout << "sum:" << revtotal << std::endl;
  return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-20
    • 2018-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-09
    • 2010-11-11
    相关资源
    最近更新 更多