Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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,

And of course, without using sizeof operator !

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

Thanks and regards Maddy

like image 805
maddy Avatar asked May 12 '10 09:05

maddy


People also ask

How do you determine data type size?

2^(n-1) is the formula to find the maximum of an INT data type. In the preceding formula N (Size in bits) is the size of data type. The ^ operator calculates the power of the value. The range of an int data type is -2,147,483,648 to 2,147,483,647.

How do you know what size you are without sizeof?

The idea is to use pointer arithmetic ( (&(var)+1) ) to determine the offset of the variable, and then subtract the original address of the variable, yielding its size. For example, if you have an int16_t i variable located at 0x0002 , you would be subtracting 0x0002 from 0x0006 , thereby obtaining 0x4 or 4 bytes.

How do you find the size of an array without sizeof?

*(a+1) => Dereferencing to *(&a + 1) gives the address after the end of the last element. *(a+1)-a => Subtract the pointer to the first element to get the length of the array. Print the size. End.


2 Answers

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/

like image 78
Thea Avatar answered Oct 15 '22 18:10

Thea


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.

like image 29
Frank Bollack Avatar answered Oct 15 '22 18:10

Frank Bollack