标签:style blog color io ar for sp div on
1 #include <stdio.h> 2 #include <string.h> 3 4 int main(void){ 5 char temp[3]; 6 scanf("%s", temp); 7 printf("%d\n", sizeof(temp)); 8 printf("%d\n", strlen(temp)); 9 printf("%s\n", temp); 10 }
编译时出错:
test_scanf.c: In function ‘main’: test_scanf.c:7:2: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long unsigned int’ [-Wformat=] printf("%d\n", sizeof(temp)); ^ test_scanf.c:8:2: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘size_t’ [-Wformat=] printf("%d\n", strlen(temp)); ^
sizeof() 和 strlen() 返回值类型为size_t
In C99‘s *printf, z is a length modifier like h or l, not a conversion specifier like d or u.
将代码改为:
printf("%zu\n", sizeof(temp)); printf("%zu\n", strlen(temp));
另外:
strlen 计算到\0 出现为止。
sizeof 保证能容纳实现所建立的最大对象的字节大小。
标签:style blog color io ar for sp div on
原文地址:http://www.cnblogs.com/iowl/p/4049955.html