c中的数组副本会以某种方式添加■甚至调试器甚至都不会显示它

问题描述 投票:0回答:1

我一直在编写代码来检查给定方面的给定字符串(任何长度)。但是我遇到了这个问题:

line_size = getline(&buffer, &buffsize, stdin);
        int length = line_size - 1;
        char input[length];
        char input_copy[length];
        printf("buffer: %s",buffer);
        for (int i = 0; i < length; i++) input[i] = buffer[i];
        printf("input: %s", input);

以某种方式给我

buffer: test
input: test▄■a

甚至调试器显示:

snipped of debugger

目前,我不知道我在做什么错。真的希望你们能帮助我。

编辑:完整程序:

int main(int argc, char *const argv[]) {
    bool ignore_white, ignore_case, has_options = false;
    char *out_path = NULL;
    char *input_path = NULL;
    int c;


    char *buffer;
    size_t buffsize = 0;
    int line_size = 0;
    buffer = NULL;


    myprog = argv[0];

    while ((c = getopt(argc, argv, "s;i;o:")) != -1) {
        has_options = true;
        switch (c) {
            case 's' :
                ignore_white = true;
                break;
            case 'i' :
                ignore_case = true;
                break;
            case 'o':
                out_path = optarg;
                break;
            default:
                usage();
                break;
        }
    }
    if (optind < argc) input_path = argv[optind]; //input_path[] and optind ++ for more then one inputpath
    if (input_path == NULL) {
        line_size = getline(&buffer, &buffsize, stdin);
        int length = line_size - 1;
        char input[length];
        char input_copy[length];
        printf("buffer: %s",buffer);
        for (int i = 0; i <= length; i++) input[i] = buffer[i];
        printf("input: %s", input);

        free(buffer);
        buffer = NULL;

    }
    return 0;
}
c arrays printf getline
1个回答
0
投票

只需添加

input[line_size] = '\0';

此循环后:

for (int i = 0; i <= length; i++) input[i] = buffer[i];

*当然将大小从input [length]更改为input [line_size]

© www.soinside.com 2019 - 2024. All rights reserved.