【问题标题】:character array printing output字符数组打印输出
【发布时间】:2023-07-11 14:52:02
【问题描述】:

我正在尝试了解打印字符数组的输出,它在 ideone.com(C++ 4.3.2) 和我的机器(Dev c++、MinGW 编译器)上为我提供了可变输出

1)

#include<stdio.h>
main()
{
    char a[] = {'s','t','a','c','k','o'};
    printf("%s ",a);
}

它在我的机器上打印“stacko”,但在 ideone 上不打印任何东西

2)

#include<stdio.h>
main()
{
    char a[] = {'s','t','a','c','k','o','v','e'};
    printf("%s ",a);
}

在 ideone 上:它仅在第一次打印“stackove”,然后在我运行此程序时不打印任何内容 在我的 dev-c 上:它打印“stackove.;||w” 当我尝试打印这种最后没有任何'\0'的字符数组时,理想的输出应该是什么,它似乎到处都给出了可变输出。请帮忙 !

【问题讨论】:

    标签: c arrays string character


    【解决方案1】:

    %s 转换说明符需要一个字符串。 字符串是一个字符数组,包含一个终止空字符'\0',它标志着字符串的结束。因此,您的程序本身会调用未定义的行为,因为 printf 超出了访问内存的数组,该数组超出了数组边界,以寻找不存在的终止空字节。

    你需要的是

    #include <stdio.h>
    
    int main(void)
    {
        char a[] = {'s', 't', 'a', 'c', 'k', 'o', 'v', 'e', '\0'};
        //                                                    ^
        // include the terminating null character to make the array a string
    
        // output a newline to immediately print on the screen as
        // stdout is line-buffered by default
        printf("%s\n", a);
    
        return 0;
    }
    

    你也可以用字符串字面量初始化你的数组

    #include <stdio.h>
    
    int main(void)
    {
        char a[] = "stackove";  // initialize with the string literal
        // equivalent to
        // char a[] = {'s', 't', 'a', 'c', 'k', 'o', 'v', 'e', '\0'};
    
        // output a newline to immediately print on the screen as
        // stdout is line-buffered by default
        printf("%s\n", a);
    
        return 0;
    }
    

    【讨论】:

    • 是的,但是正确的输出应该是什么?
    • @user2657257 在printf 中使用%s 打印数组是未定义的行为。您的程序可能会崩溃或产生不可预知的结果。