Question

I wrote some basic code

#include <iostream>
using namespace std;

int main( int argc, char *argv[] ){
    for (int i=1;i<=argc;i++){
        cout << argv[i] <<"\n";
    }
    cout <<"hello";

    return 0;
}

and when i'm running it for example with

./a.out 1 2 3

I see:

1
2
3

Why there's no "hello"?

Was it helpful?

Solution

Your loop tries to stream argv[argc], which is one after your program arguments.

In fact, it is defined to be a null pointer1, and giving streams a null pointer sets their error bit2.

Consequently, your next stream operation (cout << "hello") fails.

Loop up to argc but not including it:

for (int i = 1; i < argc; i++) {
    cout << argv[i] << '\n';
}

Footnote 1

[C++11: 3.6.1/2]: [..] The value of argv[argc] shall be 0. [..]

Footnote 2

[C++11: 27.7.3.6.4/3]: Requires: s shall not be a null pointer

When it is, the behaviour is undefined; GCC chooses to trap the condition and set the stream's error bit — see https://stackoverflow.com/a/7019483/560648.

OTHER TIPS

you're referencing argv[argc] which is beyond the array.

Change your for statement to:

for (int i=1;i<argc;i++){
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top