print bits of a void pointer

后端 未结 6 2167
[愿得一人]
[愿得一人] 2021-01-23 01:52

If I create a void pointer, and malloc a section of memory to that void pointer, how can I print out the individual bits that I just allocated?

For example:



        
6条回答
  •  天涯浪人
    2021-01-23 02:28

    void* p = malloc(24); allocates 24 bytes and stores the address of first byte in p. If you try to print the value of p, you'll be actually printing the address. To print the value your pointer points to, you need to dereference it by using *. Also try to avoid void pointers if possible:

    unsigned char *p = malloc(24);
    // store something to the memory where p points to...
    for(int i = 0; i < 24; ++i)
        printf("%02X", *(p + i));
    

    And don't forget to free the memory that has been allocated by malloc :)

    This question could help you too: What does "dereferencing" a pointer mean?

提交回复
热议问题