首页 > 其他 > 详细

sizeof 和 strlen 的printf 问题

时间:2014-10-25 13:11:24      阅读:244      评论:0      收藏:0      [点我收藏+]

 

 

 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 保证能容纳实现所建立的最大对象的字节大小。

sizeof 和 strlen 的printf 问题

原文:http://www.cnblogs.com/iowl/p/4049955.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!