开发者

How can you find the size of a datatype without creating a variable or pointer, or using sizeof of the datatype?

开发者 https://www.devze.com 2022-12-30 04:20 出处:网络
The question shown below is an interview question: Q) You are given/have a datatype, say X in C. The requirement is to get the size of the datatype, without declaring a

The question shown below is an interview question:

Q) You are given/have a datatype, say X in C.

The requirement is to get the size of the datatype, without declaring a variable or a pointer variable of that type,

A开发者_开发百科nd of course, without using sizeof operator !

I am not sure if this question has already been asked on SO.

Thanks and regards Maddy


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

The original is from this discussion. http://www.linuxquestions.org/questions/programming-9/how-to-know-the-size-of-the-variable-without-using-sizeof-469920/


This should do the trick:

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

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

  • assuming a sizeof(X) would return 12 (0x0c) because of alignment
  • ((X*)0) makes a pointer of type X pointing to memory location 0 (0x00000000)
  • + 1 increments the pointer by the the size of one element of type X, so pointing to 0x0000000c
  • the expression (size_t)() casts the address, that is given by the expression (((X*)0) + 1) back to an integral type (size_t)

Hope that gives some insight.


Declare a structure with a member of that type, then use offsetof to compute the size?

struct outer
{
     X x;
     char after;
};

offsetof(outer, after) should give you the (aligned) size of x. Note that I'm not declaring a variable of that type per se, nor a pointer to the type, but I'm including it as a member of a structure declaration, where I measure the location of the member that comes after it.

The offsetof macro can be defined as

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


You can typecast 0 (or any arbitrary value) to type datatype X* to find the size of the datatype, just like the below example:

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


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

精彩评论

暂无评论...
验证码 换一张
取 消