简体   繁体   中英

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.

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).

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] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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