如何在给定位置取消引用void指针的内容

时间:2015-03-23 01:53:23

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

在下面的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”或“&amp;”在我的输出中。

2 个答案:

答案 0 :(得分: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);
    }
}

答案 1 :(得分:0)

您需要更改上述代码

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);

这将对长指针(long *)进行类型转换(数组+ k)。 并且* dataPointer将取消引用长指针以打印内容。