繁体   English   中英

C 程序产生奇怪的输出

[英]C program produces weird output

在我学习 CI 的过程中,我决定创建一个结构体,该结构体给出了我在其中提供的鱼的大小,我的问题是为什么当我编写这段代码时:

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

struct fish
    {
        char catfish[9]; //reserve memory for 9 chars
        char goldfish[10]; //reserve memory for 10 chars
        char mackrel;
        char oldfish;
    };

int main()
{
    struct fish typeof_fish;

    strcpy(typeof_fish.catfish, "Big Fish\n");
    strcpy(typeof_fish.goldfish, "Small Fish\n");
    printf("%s\n", typeof_fish.catfish);

    return 0;


}

输出产生“大鱼小鱼”输出在这里

然而,当我重写最上面的一段代码并更改 char catfish[9] 时 烧焦鲶鱼[10]

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

struct fish
    {
        char catfish[10]; //reserve memory for 10 chars
        char goldfish[10]; //reserve memory for 10 chars
        char mackrel;
        char oldfish;
    };

int main()
{
    struct fish typeof_fish;

    strcpy(typeof_fish.catfish, "Big Fish\n");
    strcpy(typeof_fish.goldfish, "Small Fish\n");
    printf("%s\n", typeof_fish.catfish);

    return 0;


}

在这里产生“大鱼”输出

提前感谢您对这个令人费解的错误的回答

当您 strcpy "Big Fish\\n"时,您没有为catfish[9]的空终止符留出足够的空间。 该字符串有 9 个字符长,这意味着您需要一个大小为 10 的缓冲区来存储空终止符。

如果字符串错过了空终止符,则输出具有未定义的行为,因为程序无法知道字符串在哪里结束。

当您执行第一次复制时, strcpy()总共复制 10 个字节(来自字符串本身的 9 个字节加上终止符)。 由于您在catfish只分配了 9 个字节,因此终止符进入goldfish的第一个字节,然后在您复制第二个字符串时被覆盖。 因此,当您执行catfishprintf()时,它不会在catfish的末尾停止,而是继续打印,直到在goldfish的末尾找到终止符。

在第二种情况下,您为终止符添加了足够的空间,以免被覆盖,因此当您打印时,它只会按预期打印catfish的内容。

暂无
暂无

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

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