calculating size of int

Hi,
Is there any way to calculate the size of a built in data type without using 'sizeof' operator? I also don't have the option to read it from std .h file.

regards
Apoorva Kumar

You cannot really calculate it; it is a given for each implementation. What platform/compiler are you running?

declare a pointer of that type , say like this..

TYPE *ptr;
t=(ptr+1)-(ptr);

   now this value of t gives the sizeof TYPE in bytes i haven't tried it but it should work

regards
- vijay

What happened with sizeof (just interesting)?

Dear Hitori,
The platform is solaris and there is some problem due to which we cannot use sizeof ( i am not very clear about the reason, somebody from my team needs this. So we can think this has been lost ).

Dear Vijay,
The basic of pointer airthmetic tells me that i will get t=1 by doing
t=(ptr+1)-(ptr).

Anyway guys, thanks a lot for sparing time to look at this question.

with regards
Apoorva Kumar

May be this will work

int t;
t=(int)(ptr+1)-(int)(ptr);

This code works correctly on 3 different platforms. I think your co-worker is mis-informed somehow. The problem with this is that it is run-time only, not compile-time like sizeof().

#include <stdlib.h>
/* struct example change it for each struct */
typedef struct
{
    char a[10];
    int  b;
} mystruct_t;

size_t dbl_size=0;
size_t int_size=0;
/* ISO C has CHAR_BIT fixed to eight bits.  If it's an 8 bit per byte machine, char = 1 byte */
size_t char_size=0; 
size_t mystruct_t_size=0;

unsigned long diff(const void *a, const void *b)
{
	unsigned long diff=((unsigned char *)b - (unsigned char *)a);
	return diff;
}

void set_sizes(void)
{
	unsigned char *p=NULL;
	int arr1[2];
	double arr2[2];
	mystruct_t arr3[2];
	char arr4[2];
	dbl_size=diff(&arr2[0],&arr2[1]);
	int_size=diff(&arr1[0],&arr1[1]);
	mystruct_t_size=diff(&arr3[0],&arr3[1]);
	char_size=diff(&arr4[0],&arr4[1]);
}

int main()
{
	set_sizes();
	printf("dbl_size=        %u\n",dbl_size);
	printf("int_size=      	 %u\n",int_size);     
	printf("char_size=       %u\n",char_size);
	printf("mystruct_t_size= %u\n",mystruct_t_size);
	return 0;                      
}

#include <stdio.h>

int main(int argc, char **argv) {

        int i;
        int j = (int)(&i+1)-(int)&i;
        printf ("(int)(&i+1)-(int)&i= %d\n", j);
        printf ("sizeof(i)= %d\n", sizeof(i));

        return 0;
}

output (for instance only):

(int)(&i+1)-(int)&i= 4
sizeof(i)= 4

Seems it will work!! Thanks a lot Jim and Hitori!!

regards
Apoorva Kumar

I'm not a fan of hacks, and the above certainly seems like a hack. sizeof was created for a reason, use it, love it. I have *no* idea why sizeof won't work, but I'd seriously try to figure that out before hacking it.

I'm guessing they want to use it at compile time, so they can do things like

#if SIZEOF_HACK(int) < 4
#error "Don't have 32-bit integers!"
#endif

but that's just a guess.