Amit Singh Tomar
Amit Singh Tomar

Reputation: 8610

Why address is type casted to char *?

I am reading one of the implementation of finding out the size of a variable without using sizeof() Following is the implementation

int i = 1;
size_t size = (char*)(&i+1)-(char*)(&i);
printf("%zi\n", size);

But I don't understand why address of varibale i is type casted to (char *) not to (int *).

Can any one help me understanding how this type caste is working here?

Upvotes: 2

Views: 206

Answers (4)

humam
humam

Reputation: 191

Both addition and subtraction have a different behavior with pointers according to the size of the data type to which they point. For example, let's assume that in a given compiler for a specific machine, char takes 1 byte, short takes 2 bytes and long takes 4. Suppose we define the following variables:

char *pChar;
short *pShort;
long *pLong;

and that we know that they point to memory locations 1000, 2000 and 3000 respectively, so if we write:

pChar++;  // As expected, pChar will contain the value 1001
pShort++; // pShort will contain the value 2002, because short type will take 2 bytes
pLong++;  // pLong will contain the value 3004

Back to code in the question, according to the pointer arithmetic, the variable size will contain the size of i (in this case int) regardless the cast to (char *) or (int *)

Upvotes: 0

LearningC
LearningC

Reputation: 3162

size_t size = (char*)(&i+1)-(char*)(&i);

here since i is integer pointer, &i+1 will increment the pointer to the next address for a int type variable. So this increment will result in increment of address by the number of bytes required store a int data. but if you directly subtract the value it will give you number of int data in between pointers not the number of bytes. So to get the number of bytes you type cast the pointer to a data type whose size is a byte.
You can even convert it to a integer and get the difference to get the size of int i.e. number of bytes. but it will result in warning so not a good practice.

Upvotes: 2

Marius Bancila
Marius Bancila

Reputation: 16338

The size of char is guaranteed to be 1. If you convert the pointer from int to char, when you subtract the two pointers you get the different between them which will be in units of size of char, not size of int. It helps to figure the actual size of an int.

Upvotes: 3

Bathsheba
Bathsheba

Reputation: 234795

The casts to (char*) mean that the difference is computed in char pointer arithmetic. The resulting size will then be in units of char (i.e. bytes), which is the natural unit of a sizeof.

Upvotes: 8

Related Questions