2014-12-19 105 views
2

使用sizeof运算符与“snprintf”是否合适? 例如在snprintf中使用sizeof运算符是否正确

char cstring[20]; 
    snprintf(cstring,sizeof(cstring),"%s","somestring......"); 
+1

您已经标记用'C++'你的问题。实际上,在C++中,如果可能的话,我们不会使用'snprintf',而是使用'std :: ostringstream'。如果您只是对C解决方案感兴趣,请考虑删除'C++'标签。 – 5gon12eder 2014-12-19 07:00:33

+1

你为什么认为这不好? – 2014-12-19 07:06:17

+0

@EdHeal它看起来很好,但我只想确认(任何平台在任何平台上都面临任何问题) – 2014-12-19 07:11:26

回答

5

是的,这很好,您发布的具体情况是不同的,你不检查返回值,这样你就不会知道,如果该字符串被截断好。

2

是的,你可以使用。但是,如果字符串高于sizeof值,则该字符串将被截断。或者直到给定的值被存储在该数组中。

4

您可以使用snprintf中的sizeof运算符,但如果字符串的长度大于您指定的大小,则字符串中的其余字符将丢失。

4

在您发布的示例中,这很好。

然而,这不是罚款在阵列衰变到指针任何情况下:

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 
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 
相关问题