Web Toolbar by Wibiya

Pages

Tuesday, November 8, 2011

Implement sizeof() operator.

Solution #1: We know that in pointer arithmetic, incrementing or decrementing a pointer of type 't' increments or decrements it by 'size of t' respectively. Below are some examples for 32-bit architecture,

int* pInt = 0x0004;
++pInt;                 //now it points to 0x0008

double* pDouble = 0x0002;
++pDouble;         //now points to 0x000A

char* pCh = 0x0005;
++pCh;                //now points to 0x0006

Now that we know this, we can make a character pointer point to an object of type 't' and another char pointer point to 't+1' and their difference will give the size of the object. Here is the code,

#define my_sizeof(a) (size_t)((char*)(&(a)+1)-(char*)(&(a)))

struct temp {
 int i;
 float f;
 char c;
};

int main()
{
 struct temp t;
 printf("Size of t is %d\n", (int)my_sizeof(t));

 return 0;
}

3 comments:

Unknown said...
This comment has been removed by the author.
Supraja said...

Hi Suchit

Can you pl explain the macro ?

Suchit Maindola said...

Hi Supraja, I have added explanation to the post now. Let me know if something is not clear.