使用带有“snprintf”的sizeof运算符是否可以? 例如
char cstring[20];
snprintf(cstring,sizeof(cstring),"%s","somestring......");
答案 0 :(得分:7)
是的,没关系,你发布的具体案例很好,除非你没有检查返回值,所以你不知道该字符串是否被截断。
答案 1 :(得分:5)
你发布的例子很好。
但是,在数组衰减到指针的任何情况下都不行:
void func(char s []) {
snprintf(s,sizeof(s),"%s","somestring......"); // Not fine, s is actually pointer
}
int main(void) {
char cstring[20];
func(cstring); // Array decays to pointer
答案 2 :(得分:4)
您可以在sizeof
中使用snprintf
运算符,但如果字符串的长度大于您指定的大小,则字符串中的其余字符将丢失。< / p>
答案 3 :(得分:2)
是的,你可以使用。但是如果字符串高于sizeof值,则字符串将被截断。或者直到给定的值存储在该数组中。
答案 4 :(得分:1)
#include <stdio.h>
int main()
{
char str[16];
int len;
len = snprintf(str, sizeof( str ), "%s %d %f", "hello world", 1000, 10.5);
printf("%s\n", str);
if (len >= 16)
{
printf("length truncated (from %d)\n", len);
}
}
output:
=======
./a.out
hello world 100
length truncated (from 26)
/* You can see from the output only 15 char + '\0' is displayed on the console ( stored in the str ) */
/* Now changing the size of the str from 16 to 46 */
#include <stdio.h>
int main()
{
char str[46];
int len;
len = snprintf(str, sizeof( str ), "%s %d %f", "hello world", 1000, 10.5);
printf("%s\n", str);
if (len >= 46)
{
printf("length truncated (from %d)\n", len);
}
}
output:
==========
./a.out
hello world 1000 10.500000