【问题标题】:Read access violation when attempting strcpy from file buffer to char array尝试从文件缓冲区到字符数组的 strcpy 时读取访问冲突
【发布时间】:2019-04-16 08:42:33
【问题描述】:

我一直在做一个实现散列的任务。在其中,我通读了一个名为“蛋白质”的文本文件。当我尝试将其复制到另一个 char 数组时会出现问题。 Visual Studio 引发读取访问冲突。

#include <iostream>
#include <fstream>
using namespace std;
struct arrayelement {
  char protein[30];
  int count;
}; 
arrayelement proteins[40];
int main()
{
  char buffer[30];

  // open source file
  ifstream fin("proteins.txt");
  if (!fin) { cerr << "Input file could not be opened\n"; exit(1); }

  // loop through strings in file
  while (fin >> buffer) {
    int index = ((buffer[0] - 65) + (2 * (buffer[strlen(buffer)-1] - 65)) % 40);
    while (true)
    {
        if (proteins[index].protein == buffer)  // Found
        {
            proteins[index].count++;
            break;
        }
        if (proteins[index].protein[0] == 0)    // Empty
        {
            strcpy(proteins[index].protein, buffer); // <-- The error in question
            proteins[index].count++;
            break;
        }
        index++;                                // Collision
     }
  }

  // close file
  fin.close();


  for (int i = 0; i <= 40; i++)
  {
    cout << proteins[i].protein << "\t" << proteins[i].count << "\n";
  }
}

【问题讨论】:

  • 你试过调试这个吗?发生错误时,索引可能为 40。
  • 也可以使用std::stringstd::vector&lt;arrayelement&gt;
  • proteins[index].protein == buffer 这不是您想要比较 char 数组的方式。
  • @0x5453 天哪,我太累了。做到了。将其更改为 strcmp 后,它全部运行。谢谢!
  • @Noctimor 因为您在使用 C++ 时尝试使用 C。使用容器....

标签: c++ arrays file char strcpy


【解决方案1】:

如果您在此处获得超过 30 个字符:

while (fin >> buffer) {

...或者如果 index >= 40 这里:

strcpy(proteins[index].protein, buffer);

...程序可能会崩溃(未定义的行为)。另外,这些char* 不会指向同一个地址,所以比较会失败:

proteins[index].protein == buffer

【讨论】:

  • 是的,这是我的比较。重写后,一切正常。这里的部分代码是根据作业给出的——我们正在使用的示例保证不超过 30,并且给出的索引是练习碰撞解决所需的两倍。否则我也绝对会清理那些东西。谢谢!
  • 太棒了!注意:如果输入字符串为"z",则索引公式将得出 91。它会变成:index = 57 + 114 % 40 => 57 + (114 % 40)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-19
相关资源
最近更新 更多