How to find the size of a variable without using sizeof
Suppose I have declared a variable "i" of a specific data type (can be int, char, float or double) ...
NOTE. Just think that "i" is declared and doesn't care if it's int or char or float or double datatype. Since I want to use a generic solution, I just mention that the variable "i" can be any of the data types, namely int, char, float or double.
Now I can find the size of the variable "i" without the sizeof operator?
source to share
You can use the following macro, taken from here :
#define sizeof_var( var ) ((size_t)(&(var)+1)-(size_t)(&(var)))
The idea is to use pointer arithmetic ( (&(var)+1)
) to determine the offset of a variable, and then subtract the original address of the variable, giving its size. For example, if you have a variable int16_t i
located in 0x0002
, you will subtract 0x0002
from 0x0006
, thus getting 0x4
or 4 bytes.
However, I really don't see a compelling reason not to use sizeof
, but I'm sure you should have one.
source to share
Program for determining the size of a variable without using an operator sizeof
#include<stdio.h>
int main()
{
int *p,*q;
int no;
p=&no;
printf("Address at p=%u\n",p);
q=((&no)+1);
printf("Address at q=%u\n",q);
printf("Size of int 'no': %d Bytes\n",(int)q-(int)p);
char *cp,*cq;
char ch;
cp=&ch;
printf("\nAddress at cp=%u\n",cp);
cq=cp+1;
printf("Address at cq=%u\n",cq);
printf("Size of Char=%u Byte\n",(int)cq-(int)cp);
float *fp,*fq;
float f;
fp=&f;
printf("\nAddress at fp=%u\n",fp);
fq=fp+1;
printf("Address at fq=%u\n",fq);
printf("Size of Float=%u Bytes\n",(int)fq-(int)fp);
return 0;
}
source to share