使用强制转换取消引用void指针

时间:2015-07-16 05:13:28

标签: c pointers void-pointers

我正在尝试使用void指针,我遇到了以下问题。当我编译下面的代码时,它没事,但是当我在我的机器上运行它时它不会给我结果而不是提示程序已经停止工作了(https://drive.google.com/file/d/0B1mLcnk8kTFUeEtmYnlOaWJ6T3c/view?usp=sharing),我不能弄清楚幕后发生了什么,解除引用void指针是否有任何问题。

如果我使用注释代码而不是原始代码,它将继续工作。

 #include<stdio.h>
 int main()
 {
     void* ptr;
     int dupe = 5;
     *(int* )ptr = dupe;  // ptr = &dupe;
      printf("The value at ptr is %3d",*(int* )ptr);
 }

我在CodeBlocks上使用gcc。

4 个答案:

答案 0 :(得分:3)

6.       *(int* )ptr = dupe;  // ptr = &dupe;

指针ptr未指向有效的内存位置。你在评论中写的是你应该做的。

语句ptr = &dupe将使ptr指向变量dupe的内存位置。

答案 1 :(得分:1)

在这里,您尝试取消引用指针而不为其分配内存。这导致segmentation faultundefined behaviour

int main(int argc, char *argv[])
{
    void* ptr;
    int dupe = 5;
    ptr = malloc(sizeof(dupe)); /* alloc memory for ptr */
    *(int* )ptr = dupe;
    printf("The value at ptr is %3d",*(int* )ptr);
    free(ptr);
    return 0;

}

如果您不打算分配内存,那么只需在代码中将*(int* )ptr = dupe;替换为ptr = &dupe,因为现在ptr将指向变量{{的有效内存位置1}}。
有关未定义行为的更多详细信息,请参阅this

答案 2 :(得分:1)

1. void* ptr; --->ptr is a void pointer that means it can hold an address of any data type, but currently it is not pointing to any address.
2. *(int* )ptr = dupe ---> ptr point to no where and you are trying to put a value which is not valid.
3. ptr = &dupe; --> in this case ptr will point to address of dump which is a valid one.

答案 3 :(得分:0)

指针int *ptr,通常是地址值,就像一个框的编号。此处int是框类型,它暗示此框用于放置int。当然,您也可以小心来投射其他类型的内容,例如(otherKindType*)ptr。 当尝试使用*ptr = someValue推荐一个指针时,就像获取框内的对象一样,你应该保证它指向一个准确的位置。

Code1(可以工作):

#include<stdio.h>
int main()
{
    void* ptr; // ptr is a pointer, it should point to somewhere 
    int dupe = 5; // a box (named dupe) fitted for int which hold 5
    ptr = &dupe; // ptr points to that box named dupe
    printf("The value at ptr is %3d",*(int* )ptr); // get content inside the box
}

Code2(不工作):

#include<stdio.h>
int main()
{
    void* ptr;// pointer, point to a random place
    int dupe = 5;
    *(int* )ptr = dupe; // To put 5 to the box that pointed by ptr
                        // But now, ptr still points to a random place
                        // oops! To write to a random box is dangerous!
                        // It will cause error like `BUS error`
                        // Sometimes, to read a random box can output wired value.
    printf("The value at ptr is %3d",*(int* )ptr);
}

Code3(可以工作):

#include<stdio.h>
int main()
{
    void* ptr;
    int dupe = 5; 

    int new_box;//added         
    ptr = &new_box;//added, now ptr points to new_box        

    *(int* )ptr = dupe; // To put 5(content of dupe) to the box that pointed by ptr
                        // That is to put 5 to new_box
    printf("The value at ptr is %3d",*(int* )ptr); // get content inside the box
}