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/