gpt4 book ai didi

c - 这段代码如何计算数据类型的 sizeof ?

转载 作者:行者123 更新时间:2023-12-02 08:55:53 24 4
gpt4 key购买 nike

#include <stdafx.h>
#include <stdio.h>
#include <conio.h>
#include<stdlib.h>
#define My_Sizeof(type) ((char*)((type*)0 +1) - (char*)(type*)0)
void main()
{
char a='1';
int b=My_Sizeof(int);
printf("size is %d",b);
_getch();
}

//有人可以帮助我理解宏如何计算 sizeof char 数据类型吗?

最佳答案

分解:

#define My_Sizeof(type) ((char*)((type*)0 +1) - (char*)(type*)0)

(char*)(type*)0 为零

(type*)0 +1 使用 (type *) 类型的指针进行指针算术,因此 (type *)0 + 1 将是一个偏移量正好为 0 + 1 * sizeof(type) = sizeof(type) bytes

的指针

当差异被视为(type *)时,差异为1。当对两种类型 (char *) 进行差异时,差异为 sizeof(T) - 0 = sizeof(T)

关于c - 这段代码如何计算数据类型的 sizeof ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4976633/

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