C - Find the size of the structure

I was asked how the question is about the interview. I could not answer.

Write C to find the size of the structure without using an operator sizeof.

+5
source share
7 answers
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;
}
+12
source

Here is another approach. It is also not fully defined, but will 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;
}
+4
source

sizeof ( vs. ), , , 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))

, - , sizeof . ( , .)

+1
source

Here is another approach ... no need to create any instance of the structure.

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

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

How it works?

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

For people who like C macro style coding, here is my example:

#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));
}
0
source
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;
}
0
source
struct  ABC

{

int a;

float b;

char c;

};


void main()
{

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

ptr++;

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

}
-2
source

All Articles