使用sizeof運算符與「snprintf」是否合適? 例如在snprintf中使用sizeof運算符是否正確
char cstring[20];
snprintf(cstring,sizeof(cstring),"%s","somestring......");
使用sizeof運算符與「snprintf」是否合適? 例如在snprintf中使用sizeof運算符是否正確
char cstring[20];
snprintf(cstring,sizeof(cstring),"%s","somestring......");
是的,這很好,您發佈的具體情況是不同的,你不檢查返回值,這樣你就不會知道,如果該字符串被截斷好。
是的,你可以使用。但是,如果字符串高於sizeof值,則該字符串將被截斷。或者直到給定的值被存儲在該數組中。
您可以使用snprintf
中的sizeof
運算符,但如果字符串的長度大於您指定的大小,則字符串中的其餘字符將丟失。
在您發佈的示例中,這很好。
然而,這不是罰款在陣列衰變到指針任何情況下:
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
#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
您已經標記用'C++'你的問題。實際上,在C++中,如果可能的話,我們不會使用'snprintf',而是使用'std :: ostringstream'。如果您只是對C解決方案感興趣,請考慮刪除'C++'標籤。 – 5gon12eder 2014-12-19 07:00:33
你爲什麼認爲這不好? – 2014-12-19 07:06:17
@EdHeal它看起來很好,但我只想確認(任何平臺在任何平臺上都面臨任何問題) – 2014-12-19 07:11:26