简体   繁体   English

C - 找出结构的大小

[英]C - Find the size of structure

I was asked this as interview question. 我被问到这是面试问题。 Couldn't answer. 无法回答。

Write a C program to find size of structure without using the sizeof operator. 编写C程序以查找结构大小而不使用sizeof运算符。

struct  XYZ{
    int x;
    float y;
    char z;
};

int main(){
    struct XYZ arr[2];
    int sz = (char*)&arr[1] - (char*)&arr[0];
    printf("%d",sz);
    return 0;
}

Here's another approach. 这是另一种方法。 It also isn't completely defined but will still work on most systems. 它也没有完全定义,但仍适用于大多数系统。

typedef struct{
    //  stuff
} mystruct;

int main(){
    mystruct x;
    mystruct *p = &x;

    int size = (char*)(p + 1) - (char*)p;
    printf("Size = %d\n",size);

    return 0;
}

Here is another approach.... no need to create any instance of structure. 这是另一种方法......不需要创建任何结构实例。

struct  XYZ{
    int x;
    float y;
    char z;
};

int main(){
    int sz = (int) (((struct XYZ *)0) + 1);
    printf("%d",sz);
    return 0;
}

How does it work? 它是如何工作的?

((struct XYZ *)0) + 1 = zero + size of structure
                      = size of structure

Here's two macro versions for the two forms of sizeof (takes a type vs. takes a variable) that you can use for all the code you'll never write where you aren't allowed to use sizeof : 这是两种形式的sizeof的两个宏版本(采用类型与接受变量),您可以使用所有不允许使用sizeof

#define type_sizeof(t) (size_t)((char *)((t *)1024 + 1) - (char *)((t *)1024))
#define var_sizeof(v)  (size_t)((char *)(&(v) + 1) - (char *)&(v))

Perhaps with some deep magic you can combine the two into a single macro that will almost serve as a drop-in replacement in all this sizeof -less code. 也许有一些深层次的魔法可以将两者结合成一个单一的宏,将几乎成为一个简易替换这一切sizeof稀少代码。 (Too bad you can't fix the multiple-evaluation bugs.) (太糟糕了,你无法修复多重评估错误。)

struct ABC
{
    int a, b[3];
    int c;
    float d;
    char e, f[2];
};
int main()
{
    struct ABC *ptr=(struct ABC *)0;
    clrscr();
    ptr++;
    printf("Size of structure is: %d",ptr);
    return 0;
}

For people that like C macro style coding, here is my take on this: 对于喜欢C宏样式编码的人来说,这是我对此的看法:

#define SIZE_OF_STRUCT(mystruct)     \
   ({ struct nested_##mystruct {     \
         struct mystruct s;          \
         char end[0];                \
      } __attribute__((packed)) var; \
      var.end - (char *)&var; })

void main()
{
   struct mystruct {
      int c;
   };

   printf("size %d\n", SIZE_OF_STRUCT(mystruct));
}
struct  ABC

{

int a;

float b;

char c;

};


void main()
{

struct ABC *ptr=(struct ABC *)0;

ptr++;

printf("Size of structure is: %d",*ptr);

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM