argc的C分段错误

Cry*_*orm 1 c segmentation-fault

我目前正在尝试对我的CS实验室进行编码,并且遇到了我看不到的Segmentation错误.我做的是蠢事还是什么?代码应该使用命令行args("blah.exe hello world")并输出它们周围的横幅.我们班级没有C的先验知识,但是之前的数据结构课程.

示例输出

===============
= hello world =
===============
Run Code Online (Sandbox Code Playgroud)

来源:使用gcc -std = c99 -Wall bannerize.c编译

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[]) {
        if(argc <= 1) {
                return EXIT_FAILURE;
        }

        printf("TEST");
        int row_length = argc + 3; //3 for space after last word and 2 extra border chars
        for(int i = 1; i < argc; i++, row_length += strlen(argv[i]));

        printf("TEST2");
        char c;
        while((c=getchar())!=EOF) {
            printf("TEST3");
            for(int i = 1; i < argc; i++, printf("%c", c));
            printf("\n");

            printf("%c ", c);
            for(int i = 1; i < argc; i++, printf("%s ", argv[i]));
            printf("%c\n", c);

            for(int i = 1; i < argc; i++, printf("%c", c));
            printf("\n");
    }

    return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

只需在没有参数的情况下运行就可以正常工作,但添加任何命令行参数会在打印任何内容之前产生分段错误.

cni*_*tar 5

for(int i = 1; i < argc; i++, printf("%s ", argv[i]))
Run Code Online (Sandbox Code Playgroud)

这是写一个奇怪而扭曲的方式for.考虑一下当发生什么i == argc - 1.你递增它然后你访问argv[argc].哪个必然是NULL.

而不是这种神秘的(ZING!)编写for的方式,尝试使用实际的身体:

for(int i = 1; i < argc; i++) {
    printf("%s ", argv[i]);
}
Run Code Online (Sandbox Code Playgroud)

问题是只有在条件(i > argc)成立时才执行正文.