Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

casting int pointer to char pointer

Tags:

c

pointers

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.

like image 344
maddie Avatar asked Oct 04 '16 14:10

maddie


2 Answers

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.

like image 191
Sergey Kalinichenko Avatar answered Sep 19 '22 11:09

Sergey Kalinichenko


The int pointer points to a list of integers in memory. They may be 16, 32, or possibly 64 bits, and they may be big-endian or little endian. By casting the pointer to a char pointer, you reinterpret those bits as characters. So, assuming 16 bit big-endian ints, if we point to an array of two integers, 0x4142 0x4300, the pointer is reinterpreted as pointing to the string "abc" (0x41 is 'a', and the last byte is nul). However if integers are little endian, the same data would be reinterpreted as the string "ba".

Now for practical purposes you are unlikely to want to reinterpret integers as ascii strings. However its often useful to reinterpret as unsigned chars, and thus just a stream of raw bytes.

like image 28
Malcolm McLean Avatar answered Sep 20 '22 11:09

Malcolm McLean