c - 当我在我的计算机和学校计算机上编译时,消息不一样

标签 c string strlen

  1 #include <stdio.h>
  2 #include <string.h>
  3
  4 size_t  my_strlen(const char *s)
  5 {
  6         size_t  i;
  7
  8         i = 0;
  9         while (s[i])
  10                 i++;
  11         return (i);
  12 }
  13
  14 int     main()
  15 {
  16         char s[10] = "bonjour";
  17         char s2[10] = "bonjour";
  18
  19         printf("%d\n", strlen(s2));
  20         printf("%d\n", my_strlen(s));
  21         return (0);
  22 }

当我在学校的 Imac 上测试此代码时,它工作正常,但在我的 macbook Pro 上我收到此消息:

test.c:19:17: warning: format specifies type 'int' but the argument has type 'unsigned long' [-Wformat]
        printf("%d\n", strlen(s2));
                ~~     ^~~~~~~~~~
                %lu
test.c:20:17: warning: format specifies type 'int' but the argument has type 'size_t' (aka 'unsigned long') [-Wformat]
        printf("%d\n", my_strlen(s));
                ~~     ^~~~~~~~~~~~
                %zu

当我更改它时,一切都很好,但为什么我在我的个人计算机上收到此消息? (2 GHz Intel Core i7、4 Go 1333 MHz DDR3、Intel HD Graphics 3000 384 Mo)

最佳答案

更改这些语句中的格式说明符

    printf("%d\n", strlen(s2));
    printf("%d\n", my_strlen(s));

    printf("%zu\n", strlen(s2));
    printf("%zu\n", my_strlen(s));

您的程序实际上具有未定义的行为,因为您使用了不正确的格式说明符 %d,该格式说明符是为 int 类型的对象以及具有无符号类型 的对象设计的>size_t。例如,sizeof( size_t ) 可以大于 sizeof( int ),或者 size_t 对象的正值不能用 int 类型的对象表示。编译器会对此发出警告。

关于c - 当我在我的计算机和学校计算机上编译时,消息不一样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28828623/

相关文章:

c - 是否需要创建指向结构的指针数组?

c - 将数组传递给 "qsort"是如何工作的?

php strlen 显示不同长度的数组元素

c++ - strspn C++ 下的奇怪行为,为什么?

c++ - 一种从中央存储库加载 DLL 的方法

c - 使用更多内存会降低性能吗?

c - 如何在函数(c 语言)中获取 char 数组大小?

JavaScript:字符串没有像我预期的那样连接

c# - 尝试用文字 C# 替换 '

c - 在循环中使用int n = strlen(…)时出现运行时错误