Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to know size of int without sizeof [duplicate]

Tags:

c

Possible Duplicate:
size of a datatype without using sizeof

This is question asked in a C interview I wanted to know what is the correct logic for this

If you are not having a sizeof operator in C, how will you get to know the size of an int ?

like image 483
Registered User Avatar asked Dec 27 '22 18:12

Registered User


1 Answers

Use an array[*]:

int a[2];
int sizeof_int = (char*)(a+1) - (char*)(a);

Actually, due to a note in the section on pointer arithmetic, you don't even need an array, because for the purposes of pointer arithmetic an object behaves like an array of size 1, and an off-the-end pointer is legal for an array:

int a;
int sizeof_int = (char*)((&a)+1) - (char*)(&a);

[*] By which I mean, "a solution to the puzzle posed is to use an array". Don't actually use an array, use sizeof!

like image 79
Steve Jessop Avatar answered Jan 13 '23 19:01

Steve Jessop