为什么输出是这样的?

时间:2013-11-01 06:39:52

标签: c pointers

请你解释一下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;
}

3 个答案:

答案 0 :(得分:4)

这个p=(int *)(p+1);只会增加一个字节地址,因为p是一个char指针。 它应该是p=(int *)(p+4);来访问下一个整数元素。

答案 1 :(得分:2)

嗯......让我们一步一步看看,我们应该:

#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-----'

答案 2 :(得分:0)

是的......你知道。

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

是的,那都是。谢谢

相关问题