在candidateVotes.exe中以0x50E6F1C0(UCRTBASED.DLL)抛出异常.Exe:0xc00

Exception thrown at 0x50E6F1C0 (ucrtbased.dll) in CandidateVotes.exe: 0xC0000005: Access violation reading location 0x00000000

本文关键字:抛出异常 Exe 0xc00 DLL UCRTBASED exe candidateVotes 中以 0x50E6F1C0      更新时间:2023-10-16

当我尝试运行程序时,我会收到此通知。

在cantidateVotes.exe中以0x50e6f1c0(ucrtbased.dll)抛出的例外

这是我的代码:

编写一个程序,允许用户输入五个候选人的姓氏在地方选举和每个候选人获得的选票数量中。然后,该计划应输出每个候选人的姓名,收到的票数,以及候选人获得的总票数的百分比。您的计划还应输出选举的获胜者。

void main()
{
    string name[5] = { 0 };
    int votes[5] = { 0 };
    int total = 0;
    for (int i = 0; i < 5; i++)
    {
        cout << "What is the name of Candidate number " << i + 1 << "?" << endl;
        cin >> name[i];
        cout << "How many votes did " << name[i] << " receive?" << endl;
        cin >> votes[i];
        total += votes[i];
        cout << total << endl;
    }
    system("pause");
}

问题出现在这里:

string name[5] = { 0 };

这试图构造5个std::string对象的数组,第一个字符串用0初始化。

发生时,这调用以下构造函数:

basic_string(const char * const _Ptr)

,然后,一旦删除了无效指针,就会报告访问违规错误。

将null char*指针传递给std::string构造函数是未定义的行为


无需为数组提供初始化器,因为std::string默认构造函数将正确初始化每个元素:

string name[5];

如果要指示考虑初始化,则以下语法是可以的:

string name[5] = {};

string name[5]{};

最后,启用尽可能多的合理警告始终是一个好主意。在带有Level4 (/W4)的MSVC上,我会收到以下警告:

警告C6387:' param (1)'可以是'0':这不符合函数'std :: basic_string&lt&char,std :: char_traits&char> char>,std ::分配器&lt; char>> :: {ctor}'。

注意这可能避免以后避免一些混乱。

您正在尝试用null构建std::string。从name的初始化列表中删除0或完全删除初始化列表。

string name[5];