【问题标题】:How to dereference the contents of a void pointer at given locations如何在给定位置取消引用 void 指针的内容
【发布时间】:2015-05-25 23:11:56
【问题描述】:

在下面的 Print 方法中,如何在调用 Put 方法后读取数组的内容?

    //put some "pointers" in an array
    Put(void* array)
    {
            void* ptr = array;              //get starting address of array

            int k;
            for(k=1; k <= 10; k++)
            {        
                //put data in array
                ptr = Get_DataPointer();    //sample return data: 0x6703fff00000 (64-bit hex)       
                ptr += k;                   //increment address for next iteration
            }
    }

//print the contents of the array
Print(void* array)
{
        for(k=0; k < 10; k++)
        {
            long dataPointer = ((long*)(array+ k));
            printf("Pointer %i, Content=%l\n", k, dataPointer);
        }
}

我在输出中得到“0”或“&”。

【问题讨论】:

    标签: arrays pointers void-pointers dereference pointer-arithmetic


    【解决方案1】:

    它应该看起来更像

    Put(void* array)
    {
        long *ptr = (long *)array;
        int k;
    
        for(k=1; k <= 10; k++)
        {
            *ptr = Get_DataPointer(); /* you need to dereference ptr to store value */
            ptr += 1; /* increment by one to get to the next address */
        }
    }
    
    Print(void* array)
    {
        long *ptr = (long *)array;
        int k;
    
        for(k=0; k < 10; k++)
        {
            long dataPointer = *(ptr + k); /* dereference to read the value */
            printf("Pointer %i, Content=%ld\n", k, dataPointer);
        }
    }
    

    【讨论】:

      【解决方案2】:

      上面的代码需要改一下

      long dataPointer = ((long*)(array+ k));
      printf("Pointer %i, Content=%l\n", k, dataPointer);
      

      long *dataPointer = (long*)(array+ k);
      printf("Pointer %i, Content=%l\n", k, *dataPointer);
      

      这会将 (array+k) 类型转换为长指针 (long *)。 并且 *dataPointer 将取消引用长指针以打印内容。

      【讨论】:

      • Get_DataPointer() 函数在做什么?您可以发布该代码吗?在 ptr = Get_DataPointer() 行中,您似乎正在更改 ptr 以指向其他地方?那不会更新数组。只是通过您的 Print() 函数,似乎数组正在存储 long,对吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-17
      • 2012-05-23
      • 1970-01-01
      • 2012-03-25
      • 2017-11-03
      • 1970-01-01
      相关资源
      最近更新 更多