gpt4 book ai didi

c - 为什么这个指针被转换为 char 而不是任何其他指针?

转载 作者:行者123 更新时间:2023-11-30 18:19:10 27 4
gpt4 key购买 nike

在实现我自己的 sizeof 运算符时,我遇到了一个示例,如下所示。

#define my_sizeof(type) (char *)(&type+1)-(char*)(&type)
int main()
{
double x;
printf("%d", my_sizeof(x));
getchar();
return 0;
}

我不确定他们为什么在 #define 中使用 (char *) 而不是任何其他类型转换。我需要知道所述语法的确切含义。有人可以帮助我理解这个吗..?

提前致谢。

最佳答案

要理解它,您需要知道当您编写时

double d[2];
double *p = d;
p = p + 1; p is now pointing to the next double i.e. &d[1]

在内存中p已向前移动了sizeof(double)字节

如果将 p 视为字符指针,您可以获得偏移量已更改的字节数:

double d[2];
double *p = d;
char* start = (char*)p;
p = p + 1;
char* end = (char*)p;

现在 end-start 给出以字节(字符)为单位的偏移量 IOW sizeof(double)

关于c - 为什么这个指针被转换为 char 而不是任何其他指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15802872/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com