I thought at the end of the programme, il will print 3 but in fact it is 0.
Can anyone explain how it is happening ?
Here is the code :
int arr[3] = {2, 3, 4};
char *p;
p = arr;
p = (char*)((int*)(p)); // two conversion, means nothing, omit
printf("%d, ", *p); // point to 2,
p = (int*)(p+1); // point to 3 ?
printf("%d", *p);
return 0;
You are treating an array of integers like an array of chars. The line that is marked as "means nothing" actually means a lot.
When you increment char* p
by one, you shift your pointer one byte, but in order to point to the arr[1]
you need to increment it sizeof(int)
bytes. Declare p
as int* p
, then p+1
will do what you need.
Since p
is of type char, p+1
points to one byte past the start of the first integer. So when you read one byte by dereferencing p, you are reading a position in the integer array that contains a zero byte.
If you increment a pointer, it is incremented by its type's size. Here p
is character pointer, and If you increment p
it points to next character. As character is of 1 byte, p+1
points to next byte to that pointed by p
. If p
had been an integer pointer, p+1
would point to next integer i,e 3 in your code.
The following lines print char
content (here *p
) in int
format .
char *p;
printf("%d, ", *p);
It prints 2
because the (current) machine is little-endian (eg x86). If this code is run on a big-endian machine, it would print 0
. [For endian-ness, see http://en.wikipedia.org/wiki/Endianness ]
Exercise: If the array initialization is changed to the following, what is the expected print output?
int arr[3] = {0x1a2b3c4d, 3, 4};
Let's say we have
char * pc = 0xA0;
int * pi = 0xB0;
pc += 1; // pc = ?
pi += 1: // pi = ?
What are the new values of pc
and pi
?
Since pc
is a pointer to char
, the + 1
increments pc
by sizeof(char)
, which is 1.
However, since pi
is a pointer to int
, the + 1
increments pi
by sizeof(int)
. In 32 bit system, sizeof(int)
is typically 4, whereas in a 64 bit system, sizeof(int)
is typically 8.
pc += 1; // pc = 0xA1
pi += 1: // pi = perhaps 0xB4 or 0xB8
It is okay to experiment for knowledge and curiosity sake, but in real code, accessing the bytes of an int
by casting it to char *
is not a good idea, it leads to all sorts of endian-portability issues.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.