gpt4 book ai didi

c - snprintf 给出不同的输出

转载 作者:太空宇宙 更新时间:2023-11-04 08:49:12 26 4
gpt4 key购买 nike

为什么 snprintf 在第二种情况下给出不同的值。是不是因为任何整数限制。您能否解释一下 snprintf 的工作原理以及为什么会出现负值

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

main()
{

char buff[256];

snprintf(buff,256,"%s %d"," value",1879056981);

printf("%s",buff);

}

输出:值 1879056981

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

main()
{

char buff[256];

snprintf(buff,256,"%s %d"," value",2415927893);
printf("%s",buff);

}

输出:值-1879039403

最佳答案

这是因为整数 2415927893 在您的系统上不能用任何整数类型表示,并且您的程序中有符号溢出。

整数文字的确切类型 取决于数字的大小。 C11 定义整数文字可以是intlong intlong long int,取决于哪个适合第一个 按此顺序。

6.4.4.1 整数常量

The type of an integer constant is the first of the corresponding list in which its value can be represented.

打开编译器警告。

在我的系统上,当我用以下代码编译你的代码时,gcc 会发出警告:
gcc -std=c11 -Wall -pedantic t.c

t.c:4:1: warning: return type defaults to ‘int’ [enabled by default]
t.c: In function ‘main’:
t.c:9:4: warning: format ‘%d’ expects argument of type ‘int’, but argument 5 has type ‘long long int’ [-Wformat]
t.c:9:4: warning: format ‘%d’ expects argument of type ‘int’, but argument 5 has type ‘long long int’ [-Wformat]

关于c - snprintf 给出不同的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20274417/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com