EXC_BAD_ACCESS C++ 中的数组错误

EXC_BAD_ACCESS error with arrays in C++

本文关键字:数组 错误 C++ BAD ACCESS EXC      更新时间:2023-10-16

抱歉,如果这是一个愚蠢的问题,但我正在尝试编写一个程序,将用户输入的 7 个数字与计算机生成的 7 个数字进行比较(一种彩票模拟器)。但是,当我尝试输入用户输入的 7 个数字时,程序在第二次输入后崩溃。请帮忙,提前感谢!

这是我主要的开始:

    #include <iostream>
    #include <iomanip>
    #include "Implementation.hpp"
    using namespace std;
    int main()
    {
    string name;
    cout << "What is your name?n";
    getline(cin, name);
    while(1 != 0) //I know this will never be true, I'm just doing it       
                  //because the return statement will
    {             //end the program anyways if the user inputs 2
        int *userNums = new int[7];
        int *winningNums = new int[7];
        int cont;
        int matches;
        cout << "LITTLETON CITY LOTTO MODELn";
        cout << "--------------------------n";
        cout << "1) Play Lotton";
        cout << "2) Quit Programn";
        cin >> cont;
        if(cont == 2)
            return 0;
        getLottoPicks(&userNums);

这是getLottoPicks函数:

void getLottoPicks(int *picks[])
{
    int numsAdded = 0, choice;
    while(numsAdded <= 7)
    {
        cout << "Please input a valid number as your lotto decision.n";
        cin >> choice;
        if(noDuplicates(*picks, choice) == false)
            continue;
        *picks[numsAdded] = choice;
        numsAdded++;
    }
}

相当确定这是我尝试使用的指针的问题,但是没有它们,我实际上无法更改我不认为的数组,并且我无法让函数返回数组。

如果您使用的是C++,那么最好使用 std::vector<int> ,并在 getLottoPicks 中传递对向量的引用。

但是,您的代码应该只将int *传递给getLottoPicks,并且应该处理< 7项 - 这是经典的off-by

致电获取乐透选择:

getLottoPicks(userNums);

和新的getLottoPicks代码:

void getLottoPicks(int *picks)
{
    int numsAdded = 0, choice;
    while(numsAdded < 7)
    {
        cout << "Please input a valid number as your lotto decision.n";
        cin >> choice;
        if(noDuplicates(picks, choice) == false)
            continue;
        picks[numsAdded] = choice;
        numsAdded++;
    }
}