简体   繁体   English

C ++ EXC_BAD_ACCESS,argv []

[英]C++ EXC_BAD_ACCESS, argv[]

I've been stuck on this for a while and can't debug this EXC_BAD_ACCESS error. 我已经坚持了一段时间,无法调试此EXC_BAD_ACCESS错误。 I have run NSZombie and I am pretty sure its a memory issue with argv[1] (or anything more for that matter). 我已经运行了NSZombie,并且我很确定它是argv[1]的内存问题(或其他任何问题)。 I've checked my syntax and libraries so I don't know why it wont store past arg[0] . 我已经检查了我的语法和库,所以不知道为什么它不会存储过去arg[0]

#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;

int main(int argc, char* argv[])
{
    cout << "Enter the initial bankroll" << endl;
    int bankroll = atoi(argv[1]); //code faults here

    cout << "Enter seed" << endl;
    int seed = atoi(argv[2]);

    // ...

I left out the rest because the error occurs before anything else. 我忽略了其余部分,因为错误首先发生。

The code runs in the terminal but fails the automatic grader for my class. 该代码在终端中运行,但未通过我的课程的自动平地机。

Arguments entered: 输入的参数:

./blackjack 400 1 ./二十一点400 1

Should work for any numbers. 应该适用于任何数字。

Shouldn't argv[0] would be blackjack, argv[1] the first number and argv[2] the second? argv[0]应该是二十一点, argv[1]是第一个数字, argv[2]是第二个数字吗?

cout doesn't fill the elements of argv , those come from the command line used to execute your program. cout 不能填充argv的元素,这些元素来自用于执行程序的命令行。 Also, whenever you use argv , be sure to check argc , which is the number of valid indices into argv . 另外,每当您使用argv ,请务必检查argc ,这是argv中有效索引的数量。 Your program is probably crashing because you haven't passed any arguments to your program, and so the elements of argv aren't usable. 您的程序可能崩溃,因为您没有向程序传递任何参数,因此argv的元素不可用。

You'll need to use cin calls to read the user input that you're expecting, or change your program to use values passed in from the command line, ie no prompts or reads. 您将需要使用cin调用来读取所需的用户输入,或将程序更改为使用从命令行传入的值,即不提示或不读取。

Your added assumptions are correct about argv : if you execute the program with: ./blackjack 400 1 , then argv[1] should be 400 , and argv[2] should be 1 . 您添加的关于argv假设是正确的:如果使用./blackjack 400 1执行程序,则argv[1]应该为400 ,而argv[2]应该为1

Since, based on your edit, you seem to want to get these numbers from the command-line, then remove your cout calls. 因为根据您的编辑,您似乎想从命令行获取这些数字,然后删除您的cout调用。

As others have noted argv are command line arguments. 正如其他人指出的,argv是命令行参数。 If they are filled you just use them. 如果它们已满,请使用它们。 I often do like this: 我经常这样:

int
main(int n_app_args, char** app_arg)
{
  std::string nec_file;
  if (n_app_args > 1)
    nec_file = app_arg[1];
  else
  {
    std::cout << "Enter NEC output file: ";
    std::cin >> nec_file;
  }

where if I forget the command line argument the program asks me. 如果我忘记了命令行参数,程序就会问我。 If I remember the argument the argument is used without further intervention. 如果我记得该论点,则无需进一步干预即可使用该论点。 You can obviously extend this to more arguments. 您显然可以将其扩展为更多参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM