C programming: casting a void pointer to an int?

后端 未结 3 738
谎友^
谎友^ 2021-02-02 11:27

Say I have a void* named ptr. How exactly should I go about using ptr to store an int? Is it enough to write

ptr = (void *)5;

If I want to sav

3条回答
  •  名媛妹妹
    2021-02-02 12:00

    You're casting 5 to be a void pointer and assigning it to ptr.

    Now ptr points at the memory address 0x5

    If that actually is what you're trying to do .. well, yeah, that works. You ... probably don't want to do that.

    When you say "store an int" I'm going to guess you mean you want to actually store the integer value 5 in the memory pointed to by the void*. As long as there was enough memory allocated ( sizeof(int) ) you could do so with casting ...

    void *ptr = malloc(sizeof(int));
    *((int*)ptr) = 5;
    
    printf("%d\n",*((int*)ptr));
    

提交回复
热议问题