我正在尝试记录用户输入的笔记并将其存储在数组中。验证工作正常,但是当我在循环中输入最后一个值时,我得到:

Debug Assertion Failed!
Expression: "(_Ptr_user & (_BIG_ALLOCATION_ALIGNMENT - 1))==0"&&0
An invalid parameter was passed to a function that considers invalid parameters fatal.

我正在努力了解问题出在哪里以及如何解决。
#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

typedef string noteName;

noteName getNoteName(int i)
{
    bool flag = true;
    noteName Namein;

    do
    {
        cout << "Please enter note name no. " << i + 1 << ": ";
        cin >> Namein;
        cout << "------------------------------------\n";

        if (Namein.length() > 3 || Namein.length() < 2)
        {
            cout << "Sorry, a note name must be 2 or 3 characters long. Please try again.\n";
            flag = false;
        }
        else if (Namein.length() == 3 && Namein[1] != '#')
        {
            cout << "Sorry, the second character of a sharp note name must be #. Please try again.\n";
            flag = false;
        }
        else if ((Namein[0] < 'a' || Namein[0] > 'g') && (Namein[0] < 'A' || Namein[0] > 'G'))
        {
            cout << "Sorry, the first character of a note name must be a letter between A and G. Please try again.\n";
            flag = false;
        }
        else if (isdigit(Namein.back()) == false)
        {
            cout << "Sorry, the last character of a note name must be a number. Please try again.\n";
            flag = false;
        }
        else
        {
            flag = true;
        }
    } while (flag == false);

    return Namein;
}

int main()
{
   const int numNotes = 4;

    noteName NoteNames[numNotes];

    cout << "Hello\n";

    for (int i = 0; i <= numNotes; i++)
    {
        NoteNames[i] = getNoteName(i);
    }

    cout << "Thank you, the note names and lengths you entered were: \n\n";

    for (int i = 0; i <= numNotes; i++)
    {
        cout << i << ". " << NoteNames[i] << "\n";
    }

    cout << "Done!";

    return 0;
}

我想说这与返回类型为getNoteName()string有关,因为我的其他任何返回int的函数都没有遇到这个问题。

最佳答案

noteName NoteNames[numNotes];定义一个数组,其中NoteNames[numNotes - 1]是您可以访问的最大元素。

您比这更进一步。这样做的行为是不确定的,表现为您观察到的崩溃。

将循环限制替换为for (int i = 0; i < numNotes; i++)或类似的名称。

(对于类名和变量名,您还具有CamelCase约定,它们与正常情况有所不同,这使您的代码难以读取。)

(我也希望看到constexpr int numNotes = 4;:Google以获得更多详细信息。)

10-08 09:16