【问题标题】:Uninitialized object? What's wrong with this code. [closed]未初始化的对象?这段代码有什么问题。 [关闭]
【发布时间】:2014-05-09 07:20:37
【问题描述】:

由于某种原因,代码会崩溃并给我一个访问冲突错误。它一直说对象用户未初始化

随机编码中 0x0F45E89A (msvcr110d.dll) 处的第一次机会异常 在 C++.exe 中:0xC0000005:访问冲突写入位置 0xABABABAB.Unhandled 异常在 0x0F45E89A (msvcr110d.dll) 在随机 C++.exe 中的编码:0xC0000005:访问冲突写入位置 0xABABABAB.

谢谢。有什么想法吗?

#include <iostream>
#include <fstream>
#include <cstring>
#include <sstream>
#include <vector>
#include <string>

using namespace std;

struct User { 
    string name; //Both first and last name go here 
    int birthYear; 
    string major; 
}; 

int main()
{
    ifstream input("input.txt");

    if(!input || !input.is_open())
        return -1;

    string buffer;
    int count = -1;
    int index = 0;
    int size;
    User* users;

    while(getline(input, buffer, '\n'))
    {
        stringstream ss(buffer);

        if(count == -1)
        {
            ss >> size;
            users = new User[size];
            count = 0;
        }
        else
        {
            if(count == 0)
            {
                users[index].name = buffer;
                count++;
            }
            if(count == 1)
            {
                ss >> users[index].birthYear;
                count++;
            }
            if(count == 2)
            {
                users[index].major = buffer;
                count = 0;
                index++;
            }
        }
    }

    for(int i = 0; i < 2; i++)
    {
        cout<<users[i].name << " " << users[i].birthYear << " " << users[i].major <<endl;
    }
    system ("PAUSE");
    return 0;
}

【问题讨论】:

  • 我认为这是因为您没有创建用户来填充您的数组。每当您尝试访问 users[index] 时,什么都没有。
  • 什么时候崩溃?您是否使用简单的cout 跟踪对其进行了调试或跟踪?您是否考虑过使用矢量来代替?您的包含路径表明您拥有。
  • ss&gt;&gt;size;之后填写std::cout&lt;&lt;size&lt;&lt;std::endl;。可能是负面的等等。
  • @user 要求调试代码转储的问题通常应该被关闭。相反,请参阅ericlippert.com/2014/03/05/how-to-debug-small-programs

标签: c++ object initialization


【解决方案1】:
for(int i = 0; i < 2; i++)
{
    cout<<users[i].name << " " << users[i].birthYear << " " << users[i].major <<endl;
}

看起来不合适。您如何确定用户至少包含两个元素。如果getline 因为badfile 失败或者第一行提示只有1 条记录,你会得到上面的异常。

您应该将循环更改为

// Initialize size with 0 before while(getline) loop
for(int i = 0; i < size; i++)
{
    cout<<users[i].name << " " << users[i].birthYear << " " << users[i].major <<endl;
}

下面的代码行看起来也有问题

if(count == 0)
{
    users[index].name = buffer;
    count++;
}
if(count == 1)
{
    ss >> users[index].birthYear;
    count++;
}
if(count == 2)
{
    users[index].major = buffer;
    count = 0;
    index++;
}

当 count 为 0 时,它会先进入 if 条件并递增。然后条件count == 1 将变为真,您还将访问下两个条件。您应该将下两个 if 条件替换为 else if 或将 switch 替换为 break 语句以查看 intended behavior

完成后释放用户也是一个好习惯。

【讨论】:

    【解决方案2】:

    我认为第一个 getline 失败(while 没有进入,所以什么都没有创建),你会自动进入 for 循环。检查您实际拥有用户的情况。

    【讨论】:

      猜你喜欢
      • 2011-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-30
      相关资源
      最近更新 更多