【问题标题】:Assigning an array with std::fgetc() return使用 std::fgetc() 返回分配数组
【发布时间】:2021-12-12 18:21:27
【问题描述】:

我正在尝试使用std::fgetc 函数存储.awv 文件的第一个4 chars

这就是我所拥有的

FILE* WAVF = fopen(FName, "rb");
std::vector<std::string> ID;
ID[4];
for (int i = 0; i < 4; i++)
{
    ID[i] = fgetc(WAVF);
}

我不断收到此错误:

Exception thrown at 0x00007FF696431309 in ConsoleApplication3.exe: 
0xC0000005: Access violation writing location 0x0000000000000010.

【问题讨论】:

    标签: c++ string c++11 wav riff


    【解决方案1】:

    你的程序有undefined behavior

    您的矢量ID 为空。通过在空的std::vector 上调用operator[],调用undefined behavior。你很幸运,你的程序崩溃了,说“访问冲突”。

    您需要:

    // create a vector of string and initialize 4 empty strings
    std::vector<std::string> ID(4); 
    
    for (auto& element: ID)
    {
        element = some `std::string`s
    }
    

    但是,在您的情况下,std::fgetcintger 返回为

    成功时获得的字符或失败时获得EOF

    因此,您可能需要std::vector&lt;char&gt; 或(最多)std::string 等数据结构。

    【讨论】:

      猜你喜欢
      • 2013-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-17
      • 1970-01-01
      • 1970-01-01
      • 2019-07-24
      • 1970-01-01
      相关资源
      最近更新 更多