c++ - 测试结构和数组时出现 msvcr110d.dll!memcpy 错误

标签 c++ arrays dll c++11 structure

我想知道是否有人可以看看为什么我会在这里遇到运行时错误。

First-chance exception at 0x6FBDEBC2 (msvcr110d.dll) in Project1.exe: 0xC0000005: Access violation writing location 0x7CB67DEB. Unhandled exception at 0x6FBDEBC2 (msvcr110d.dll) in Project1.exe: 0xC0000005: Access violation writing location 0x7CB67DEB.

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main(){
    struct person {
        string name;
        int age;
        int weight;
        string nickname;
    } ;

    person people[1];

    for(int i = 0; i < sizeof(people); i++){
        string s[4];
        for(int x = 0; x < 4; x++){
            cout << "Please enter person " << i << "'s " << (x == 0 ? "name" : x == 1 ? "age" : x == 2 ? "weight" : x == 3 ? "nickname" : "unknown") << "." << endl;
            getline(cin, s[x]);
        }
        people[i].name = s[0];
        stringstream(s[1]) >> people[i].age;
        stringstream(s[2]) >> people[i].weight;
        people[i].nickname = s[3];
    }

    for(int i = 0; i < sizeof(people); i++)
        cout << "Person " << i << ": name = " << people[i].name << ", age = " << people[i].age << ", weight = " << people[i].weight << ", nickname = " << people[i].nickname << endl; 

    cout << "Please press enter to continue.";
    fflush(stdin);
    cin.clear();
    cin.get();
}

在第二个 for 循环之前一切正常,似乎运行错误。

最佳答案

你的问题出在这里:

sizeof(people)

这不会给您people 数组的长度,而是给您数组的总大小(以字节为单位)。您可以使用 std::begin(people)std::end(people) 使迭代器到达数组的开头和结尾。

for (auto it = std::begin(people); it != std::end(people); ++it)
{
  // it is an iterator to an element of people
  it->name = ....;
}

或者,您可以使用基于范围的循环:

for (auto& p : people)
{
  // p is a reference to an element of people here
  p.name = ....;
}

关于c++ - 测试结构和数组时出现 msvcr110d.dll!memcpy 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19252088/

相关文章:

arrays - Python如何将带有西里尔符号的字典保存到json文件中

c++ - 如何使 *.dll WinAmp 插件在 friend 的电脑上工作

c++ - 声明一个字符串数组并查找其中的元素数 (openFrameworks)

c# - 使用外部 dll 中的枚举

c++ - “The procedure entry point… could not be located” 在错误的 DLL 中

c++ - 对于巨大的稀疏对称矩阵,哪个是 Spectra 库中最快的特征值求解器?

c++ - generate_canonical 输出是否跨平台一致?

c++ - 扩展 auto_ptr 以释放一个 C 风格的对象

c++ - 为什么我无法构建此正则表达式

arrays - 解析服务器发送的数组/slice