EXC_BAD_ACCESS C++ 中的数组错误
EXC_BAD_ACCESS error with arrays in C++
抱歉,如果这是一个愚蠢的问题,但我正在尝试编写一个程序,将用户输入的 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++;
}
}
相关文章:
- 类动态数组错误
- 如何返回多维数组?错误C2440
- 数组错误(不允许类型不完整)
- C++ 将文件读取到数组错误:'operator>>'不匹配
- 不断增加的指针数组 错误:赋值中的类型不兼容
- 从文本文件读取 2D 数组错误
- 动态结构数组错误
- 旋转数组 - 错误
- 按字母顺序排序名称,数组错误
- 因为每个循环都读取数组错误
- 二维数组错误
- C 获取数组错误
- 编译时出现字符串数组错误
- c++2维指针类数组错误(使用openframework)
- C++数组错误
- C++上数组错误的大小
- C++数组错误:访问冲突读取位置0xC0000005
- c++2D数组错误
- C++:为“char [4]”数组错误获取太多初始值设定项
- 分段错误(核心转储)排序字符串数组错误