[Solved] Why does my program crash if I don’t give command line arguments to it? [closed]


It crashes because you are accessing

argv[1]

which would hold a command line argument (other than the program’s name) if there was one. You should check whether argc is greater than 1. Why greater than 1? Because the first command line argument is the name of the program itself. So argc is always greater than 0. And indexing starts at 0. So if argc == 1, only argv[0] is valid.

#include <iostream>
int main(int argc, char* argv[])
{
  // no need to check argc for argv[0]
  std::cout << argc << " " << argv[0] << "\n";
}

1

solved Why does my program crash if I don’t give command line arguments to it? [closed]