下面显示的问题是面试问题
问)你有一个数据类型,比如说C中的X.
要求是获取数据类型的大小,而不声明该类型的变量或指针变量,
而且,当然不使用sizeof运算符!
我不确定此问题是否曾在SO中提出过.
谢谢并问候Maddy
Fra*_*ack 16
这应该做的伎俩:
#include <stdio.h>
typedef struct
{
int i;
short j;
char c[5];
} X;
int main(void)
{
size_t size = (size_t)(((X*)0) + 1);
printf("%lu", (unsigned long)size);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
解释 size_t size = (size_t)(((X*)0) + 1);
sizeof(X)而返回12(0x0c)((X*)0)制作一个指向X内存位置0 的指针(0x00000000)+ 1将指针增加一个类型元素的大小X,因此指向0x0000000c(size_t)()将表达式转换为(((X*)0) + 1)整数类型(size_t)希望能给出一些见解.
小智 1
您可以将 0(或任何任意值)强制转换为数据类型 X* 以查找数据类型的大小,就像下面的示例一样:
#include <stdio.h>
struct node{
char c;
int i;
};
int main()
{
printf("Sizeof node is: %d\n", ((char *)((struct node *)0 + 1) - (char *)((struct node *)0)));
// substract 2 consecutive locations starting from 0 that point to type node,
//typecast these values to char * to give the value in number of bytes.
return 0;
}
Run Code Online (Sandbox Code Playgroud)