[英]EXC_BAD_ACCESS error with arrays in C++
sorry if this is a stupid question but I'm trying to write a program that compares 7 numbers that a user inputs to 7 numbers that the computer generates(a kind of lottery simulator). 抱歉,如果这是一个愚蠢的问题,但我正在尝试编写一个程序,将用户输入的7个数字与计算机生成的7个数字进行比较(一种彩票模拟器)。 However, when i try to input the 7 numbers that the user inputs the program crashes after the second input.
但是,当我尝试输入用户输入的7个数字时,第二次输入后程序崩溃。 Please help, and thanks in advance!
请帮助,并在此先感谢!
This is the beginning of my main: 这是我主要工作的开始:
#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 MODEL\n";
cout << "--------------------------\n";
cout << "1) Play Lotto\n";
cout << "2) Quit Program\n";
cin >> cont;
if(cont == 2)
return 0;
getLottoPicks(&userNums);
And this is the getLottoPicks function: 这是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++;
}
}
I'm fairly certain that it is a problem with the pointers that i'm trying to use, but without them I can't actually change the arrays I don't think, and I couldn't get the function to return an array. 我相当确定我要使用的指针存在问题,但是没有它们,我实际上无法更改我不认为的数组,并且我无法获得返回数组的函数。
If you're using C++, then you're probably better using a std::vector<int>
, and passing in the reference to the vector in getLottoPicks
. 如果您使用的是C ++,则最好使用
std::vector<int>
,并在getLottoPicks
传递对向量的getLottoPicks
。
However, your code should only be passing the int *
to the getLottoPicks, and should process < 7
items - it's the classic off-by one. 但是,您的代码仅应将
int *
传递给getLottoPicks,并应处理< 7
项目-这是经典的非一项。
call to getLottoPicks: 调用getLottoPicks:
getLottoPicks(userNums);
and the new getLottoPicks code: 和新的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++;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.