尝试从文件缓冲区到 char 数组的 strcpy 时读取访问冲突

Read access violation when attempting strcpy from file buffer to char array

我一直在做一项实现散列的作业。在其中,我通读了一个名为 "proteins" 的文本文件。当我尝试将它复制到另一个 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";
  }
}

如果你在这里得到超过 30 个字符:

while (fin >> buffer) {

... 或者如果这里的索引 >= 40:

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

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

proteins[index].protein == buffer