请你能解释一下 p=(int *)(p+1); 行的输出吗?
#include <stdio.h>
int main()
{
int a[3]={2,3,4};
char *p;
p=a;
p=(char *)((int*)(p));
printf("%d\n",*p);
p=(int *)(p+1);
printf("%d",*p);
return 0;
}
这p=(int *)(p+1);
只会增加一个字节地址,因为 p 是一个字符指针。应该是p=(int *)(p+4);
访问下一个整数元素。
好吧......让我们一步一步地看一下,我们应该:
#include <stdio.h>
int main()
{
/* OK, here we have an array of 3 integers. That's fine. Each
* of these is sizeof(int) bytes, typically 4 bytes. So this
* array would typically be 12 bytes long.
*/
int a[3]={2,3,4};
/* And here we have a pointer to a character. A character will
* have a size of 1 byte. */
char *p;
/* Uhm... this is suspicious. Remember, p is a pointer to
* a character, but a points to an integer. You can't mix
* potatoes and tomatoes (or things that are 4 bytes and things
* which are 1 byte. That's asking for trouble!)
*/
p=a;
/* Well... this is slightly pointless. And ugly. What do you
* think this code does? If you said "nothing" you'd be right.
*/
p=(char *)((int*)(p));
/* OK... so here you dereference the pointer p, and get
* back a single *character* (since p is a pointer to a
* character) and print that character as an integer.
*/
printf("%d\n",*p);
/* Now you increment p by one element. Since p is a
* pointer to a character, you are actually incrementing
* the address by one, since the size of a character is
* 1.
*
* But p was made to point to an array of integers and
* integers are larger than 1 byte. Typically, they are
* 4 bytes long. So now you're pointing 1 byte into an
* integer.
*/
p=(int *)(p+1);
/* And now you print whatever *CHARACTER* is at that address
* as an integer.
*/
printf("%d",*p);
return 0;
}
这个带注释的代码版本应该可以帮助您弄清楚发生了什么。如果您需要更多帮助,请考虑这个概念图,它向您展示了最后一个printf
. 每对[]
代表一个字节,箭头代表指针:
[2][0][0][0][3][0][0][0][4][0][0][0]
^ ^
a--' |
p-----'
对,你知道的。
1.如果p是指向字符的指针,p+1表示地址+1
2.如果p是指向整数的指针,p+1表示地址+4
如果 a 的地址如下
02 00 00 00 03 00 00 00 00 04 00 00 00
p=(char *)p;
这意味着现在 p 是指向字符的点。所以 p+1 表示地址 + 1
p=(int *)p+1;
所以 *p=0x03000000
是的,就是这样。谢谢