Casting int pointer to char pointer

cpointers

I've read several posts about casting int pointers to char pointers but i'm still confused on one thing.

I understand that integers take up four bytes of memory (on most 32 bit machines?) and characters take up on byte of memory. By casting a integer pointer to a char pointer, will they both contain the same address? Does the cast operation change the value of what the char pointer points to? ie, it only points to the first 8 bits of an integers and not all 32 bits ? I'm confused as to what actually changes when I cast an int pointer to char pointer.

Best Answer

By casting a integer pointer to a char pointer, will they both contain the same address?

Both pointers would point to the same location in memory.

Does the cast operation change the value of what the char pointer points to?

No, it changes the default interpretation of what the pointer points to.

When you read from an int pointer in an expression *myIntPtr you get back the content of the location interpreted as a multi-byte value of type int. When you read from a char pointer in an expression *myCharPtr, you get back the content of the location interpreted as a single-byte value of type char.

Another consequence of casting a pointer is in pointer arithmetic. When you have two int pointers pointing into the same array, subtracting one from the other produces the difference in ints, for example

int a[20] = {0};
int *p = &a[3];
int *q = &a[13];
ptrdiff_t diff1 = q - p; // This is 10

If you cast p and q to char, you would get the distance in terms of chars, not in terms of ints:

char *x = (char*)p;
char *y = (char*)q;
ptrdiff_t diff2 = y - x; // This is 10 times sizeof(int)

Demo.