just_starting
just_starting

Reputation: 1

command line arguments backwards?

So you all will probably get a chuckle but I am a newbie want to be coder that has a question. Yeah I know probably lame and obvious answer but here it is.

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

int main(int argc, char *argv[]) {
  for(int i=argc; i<=argc; i--){
    cout << argv[i] <<endl;
    }

 }

Why am I getting a segfault? And when i tweak it I get no output.

Upvotes: 0

Views: 91

Answers (2)

Spikatrix
Spikatrix

Reputation: 20244

This:

for(int i=argc; i<=argc; i--)

should be

for(int i = argc - 1; i >= 0; i--)

because

  1. Your condition for loop termination was wrong
  2. Array indices start from 0 and end at length - 1 (Note: For argv, argv[argc] is NULL)

Change >= to > if you do not want to include the first argument (the name of the program).

Upvotes: 3

R Sahu
R Sahu

Reputation: 206687

The way the for loop has been coded, i <= argc will always be true. Hence the loop will never end. As soon as i is -1, you end up accessing memory out of bounds. That is cause for undefined behavior. In your case, the undefined behavior manifests as segmentation fault.

You need to use i > 0 for the conditional of the for statement.

Remember that argv[0] is the program name. The arguments to the program start at argv[1].

Upvotes: 0

Related Questions