如何在不创建变量或指针或使用数据类型的sizeof的情况下找到数据类型的大小?

下面显示的问题是面试问题

问)你有一个数据类型,比如说C中的X.

要求是获取数据类型的大小,而不声明该类型的变量或指针变量,

而且,当然不使用sizeof运算符!

我不确定此问题是否曾在SO中提出过。

谢谢并问候Maddy

您可以类型化0(或任意值)来键入数据类型X *以查找数据类型的大小,就像下面的示例一样:

#include  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; } 

define sizeof_type(type)(size_t)((type *)1000 + 1) – (size_t)((type *)1000)

原文来自这个讨论。 http://www.linuxquestions.org/questions/programming-9/how-to-know-the-size-of-the-variable-without-using-sizeof-469920/

这应该是诀窍:

 #include  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; } 

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

希望能给出一些见解。

声明具有该类型成员的结构,然后使用offsetof来计算大小?

 struct outer { X x; char after; }; 

offsetof(outer, after)应该给你(对齐的)x的大小。 请注意,我没有声明该类型的变量本身,也没有声明指向该类型的指针,但我将其作为结构声明的成员包含在其中,我在其中测量其后面的成员的位置。

offsetof的宏可以定义为

 #define offsetof(S, f) ((size_t)(&((S *)0)->f)) 
 printf("%d",(int)(&x+1)-(int)&x