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

时间:2010-05-12 09:25:25

标签: c

以下问题是面试问题

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

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

当然,不使用sizeof运算符!

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

谢谢和问候 麦迪

5 个答案:

答案 0 :(得分:17)

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/

答案 1 :(得分: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;
}

size_t size = (size_t)(((X*)0) + 1);

的说明
  • 假设sizeof(X)由于对齐而返回12(0x0c
  • ((X*)0)生成一个指向内存位置0 X
  • 0x00000000)类型的指针
  • + 1将指针增加X类型的一个元素的大小,因此指向0x0000000c
  • 表达式(size_t)()将表达式(((X*)0) + 1)的地址强制转换为整数类型(size_t

希望能提供一些见解。

答案 2 :(得分:4)

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

struct outer
{
     X x;
     char after;
};

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

offsetof macro可以定义为

#define offsetof(S, f) ((size_t)(&((S *)0)->f))

答案 3 :(得分: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;
    }

答案 4 :(得分:0)

printf("%d",(int)(&x+1)-(int)&x