简体   繁体   English

打印 argv 后程序停止工作

[英]Program stops working after printing argv

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"?为什么没有“你好”?

Your loop tries to stream argv[argc] , which is one after your program arguments.您的循环尝试流式传输argv[argc] ,它是您的程序参数之后的一个。

In fact, it is defined to be a null pointer 1 , and giving streams a null pointer sets their error bit 2 .事实上,它被定义为一个空指针1 ,并且给流一个空指针设置它们的错误位2

Consequently, your next stream operation ( cout << "hello" ) fails.因此,您的下一个流操作 ( cout << "hello" ) 失败。

Loop up to argc but not including it :循环到argc但不包括它

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

Footnote 1脚注 1

[C++11: 3.6.1/2]: [..] The value of argv[argc] shall be 0. [..] [C++11: 3.6.1/2]: [..] argv[argc]的值应为 0。 [..]

Footnote 2脚注 2

[C++11: 27.7.3.6.4/3]: Requires: s shall not be a null pointer [C++11: 27.7.3.6.4/3]:要求: s不能是空指针

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 . GCC 选择捕获条件并设置流的错误位 - 请参阅https://stackoverflow.com/a/7019483/560648

you're referencing argv[argc] which is beyond the array.您正在引用超出数组的 argv[argc] 。

Change your for statement to:将您的 for 语句更改为:

for (int i=1;i<argc;i++){

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

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