【问题标题】:msvcr110d.dll!memcpy error while testing structures and arrays测试结构和数组时出现 msvcr110d.dll!memcpy 错误
【发布时间】:2013-10-15 15:14:17
【问题描述】:

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

Project1.exe 中 0x6FBDEBC2 (msvcr110d.dll) 处的第一次机会异常: 0xC0000005:访问冲突写入位置 0x7CB67DEB。未处理 Project1.exe 中 0x6FBDEBC2 (msvcr110d.dll) 的异常:0xC0000005: 访问冲突写入位置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)???来吧 - 你比那更清楚:) 建议:使用 std::vector 而不是数组。恕我直言...
  • 对于初学者来说,sizeof(people) 是字节,而不是元素。
  • 我是个白痴!谢谢,刚从 Java 学习 C++!

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


【解决方案1】:

你的问题在这里:

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 = ....;
}

【讨论】:

    【解决方案2】:

    为防止此类问题,请考虑这种方法,它允许您存储静态数组的大小:

    int ARRAY_SIZE = 1;
    person people[ARRAY_SIZE];
    

    然后你的for 循环:

    for(int i = 0; i < ARRAY_SIZE; i++)
    

    【讨论】:

    • 注意,数组的大小必须是编译时常量(在C++中)。
    猜你喜欢
    • 1970-01-01
    • 2021-07-06
    • 2021-04-09
    • 2021-05-18
    • 1970-01-01
    • 2023-04-07
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多