为什么 SIZE_OF_STR returns 相同的值有 2 个不同的答案?
Why SIZE_OF_STR returns 2 different answers for the same values?
为什么 SIZE_OF_STR returns "hello" 字符串的值是 7 和 5?
#include <stdio.h>
#define SIZE_OF_STR(s) sizeof(s)/sizeof(char)-1
int main()
{
char *x = "hello";
printf("%d\n",SIZE_OF_STR(x));
printf("%d",SIZE_OF_STR("hello"));
return 0;
}
输出:
7
5
第一个 sizeof 实际上是对指向 8 的 char 的指针进行 sizeof。
第二个是执行常量字符串的 sizeof,它为 "hello".
生成 6
您的宏表达式实际上在减法之前解决了除法,因此导致 8-1=7 和 6-1=5。
为什么 SIZE_OF_STR returns "hello" 字符串的值是 7 和 5?
#include <stdio.h>
#define SIZE_OF_STR(s) sizeof(s)/sizeof(char)-1
int main()
{
char *x = "hello";
printf("%d\n",SIZE_OF_STR(x));
printf("%d",SIZE_OF_STR("hello"));
return 0;
}
输出:
7
5
第一个 sizeof 实际上是对指向 8 的 char 的指针进行 sizeof。
第二个是执行常量字符串的 sizeof,它为 "hello".
生成 6您的宏表达式实际上在减法之前解决了除法,因此导致 8-1=7 和 6-1=5。