• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
verne91
博客园    首页    新随笔    联系   管理    订阅  订阅
sizeof 和 strlen 的printf 问题
printf sizeof strlen

 

 

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

posted on 2014-10-25 12:31  verne91  阅读(383)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3