【问题标题】:meaning of *( (int *)ptr+1)*( (int *)ptr+1) 的含义
【发布时间】:2013-02-19 09:21:48
【问题描述】:

假设 ptr 是某个指针,那么:

*((int *)ptr+1)

是什么意思:

首先将 ptr 类型转换为 int *,然后加一,然后取消引用。

首先将 ptr 加一,然后进行类型转换,然后取消引用。

【问题讨论】:

标签: c pointers casting type-conversion


【解决方案1】:

ptr 是指向任何东西的指针。 (int *) ptr 是指向 int 的指针,它指向与 ptr 相同的位置,但假定指针为 int(int *)ptr + 1 在内存中进一步指向一个单元格(又名一个整数)。 *((int *)ptr+1) 就是那个整数。

【讨论】:

    【解决方案2】:

    强制转换的优先级高于加法,c.f. here。因此,首先转换为整数指针,然后添加1*sizeof(int)

    【讨论】:

      【解决方案3】:

      这似乎是ptr[1] 的简短版本,当然如果ptr 是int * 指针。

      所以

      首先将 ptr 类型转换为 int *,然后加一,然后取消引用。

      【讨论】:

        【解决方案4】:

        第一个命题: 将 ptr 转换为 int*,然后加一,最后得到这个地址的 int。

        这是一种处理结构化数据的方法,例如,当您在输入中只有一个字符流时。

        【讨论】:

          【解决方案5】:
          *((int *)ptr+1)
          

          意思是:

          • 通过(sizeof(ptr)) 将指针增加到内存中的下一个位置
          • 然后将指针转换为整数指针。
          • 然后获取第一个 sizeof(int) 个字节!

          【讨论】:

            【解决方案6】:

            这段代码几乎显示了你在做什么:

            #include<stdio.h>
            
            int main( ) {
            
                int onetwo[] = { 1, 2};
                /*create a void pointer to one two*/
                void* ptr = (void*) onetwo;
            
                printf ( "pointer onetwo[0] = %p\n", &onetwo[0]  );
                printf ( "pointer onetwo[1] = %p\n", &onetwo[1]  );
            
                /* since you are doing pointer arithmetics
                 * it's really important you cast ptr back to
                 * int* otherwise the compiler might not
                 * return a pointer to onetwo[1] but if sizeof(int)
                 * is 4 bytes
                 */
                printf ( "value = %d\n", *( (int*)ptr + 1) );
            
                /* in this print statement ptr is still a void* when
                 * it is incremented, therefore it points between 
                 * onetwo[0] and onetwo[1]
                 */
            
                printf ( "value = %d\n", * ((int*)( ptr + 1)) );
            
                /*casting to int* is for illustration properties */
                printf ( "This points between onetwo[0] and onetwo[1] because it's at %p\n", (int*) (ptr + 1));
            
            
                return 0;
            
            }
            

            我机器上的输出产量:

            ~/programming/stackoverflow$ ./p
            pointer onetwo[0] = 0x7fffdd8e2fc0
            pointer onetwo[1] = 0x7fffdd8e2fc4
            value = 2
            value = 33554432
            This points between onetwo[0] and onetwo[1] because it's at 0x7fffdd8e2fc1
            

            我希望这能说明指针算法的一些效果。

            【讨论】:

              猜你喜欢
              • 2020-09-24
              • 2021-05-18
              • 2022-01-15
              • 2018-12-05
              • 2020-10-11
              • 2013-10-17
              • 2020-08-03
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多