top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to determine the size of a variable without using the sizeof operator in C/C++?

+2 votes
1,436 views
How to determine the size of a variable without using the sizeof operator in C/C++?
posted Aug 1, 2014 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

3 Answers

+2 votes
#include <stdio.h>
#define SIZEOF(x) (unsigned int)( (char *)(&x+1)-(char *)(&x) )

int main()
{
    int buf[4];
    printf("sizeof %d\n",SIZEOF(buf));

}

it works only for variable not for data type.

answer Oct 20, 2014 by Bheemappa G
+1 vote

declare two pointers.

assign the address of the variable to these two pointers.

increment any one of the pointer.

difference in addresses of these two pointers will be the size of the variable.

answer Aug 1, 2014 by Arjun Jawalkar
Adding the sample code to Arjun's answer

#include<stdio.h>
int main(){
  int *ptr = 0;
  ptr++;
  printf("Size of int:  %d",ptr);
}
Mr Salil's code is more optimized. Why use 2 pointers when the purpose is served by 1 pointer.
0 votes

Take an array of that datatype, then subtract the address of an element from the address of next element.

#include<stdio.h>
main()
{
 int a[5] = {1,2,3,4,5};
 Int size;
 size = &a[2] - &a[1];
 printf("size = %d\n",size);
}
answer Sep 18, 2014 by anonymous
...