When I run this code:
int arr[3] = {2,3,4};
char *p;
p = (char*)arr;
printf("%d", *p);
p = p+1;
printf("%d", *p);
The output is 2 and 0. The second result is slightly confusing. Could someone explain why this is happening?
Let's break this down:
int arr[3] = {2,3,4};
Creates an array of 3 integers. Assuming your system is 32bit little endian this is how it looks in memory:
02 00 00 00 03 00 00 00 04 00 00 00
char *p; p = (char*)arr;
p now points to arr but is a pointer to char*. In other words, p points to the 02.
printf("%d", *p);
You are printing as an int the location referenced by p. So when you dereference p (by writing *p) you are accessing the char (since p is of type char*) referenced by p. Which is 02.
p = p+1;
p now points to the 00 just after 02, because p is char*. So when you add 1, it will move by 1 * sizeof(char) = 1 * 1 = 1 byte in memory.
printf("%d", *p);
You are printing as an int the location referenced by p. So when you dereference p (by writing *p) you are accessing the char (since p is of type char*) referenced by p. Which is 00.
If you wanted to print 3 instead of 0 you have to change your pointer type to int* instead of char*, making the pointer move by 1 * sizeof(int) = 1 * 4 = 4 bytes in memory.
The result you get will depend on the size of int on your implementation and its endianness.
Assuming 32bit ints, 8bit chars and a litte-endian environment (say x86), arr will be like this in memory:
< arr[0] > < arr[1] > < arr[2] >
02 00 00 00 03 00 00 00 04 00 00 00
^ ^ ^
p p+1 ... p+4
If you take a char pointer to the start of that memory, and print out the first element, 2 should be output. If you increment that pointer, 0 will be output next. You'll need to increment it a few times more to 'see' 3.
Note that on a big-endian environment with the same type sizes, your program would have output two zeros, because the layout would have been:
< arr[0] > < arr[1] > < arr[2] >
00 00 00 02 00 00 00 03 00 00 00 04
^ ^ ^
p p+1 ... p+4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With