Thread: why need to cast void* ?

  1. #1
    Registered User
    Join Date
    Jul 2018
    Posts
    3

    why need to cast void* ?

    Currently studying through how pointers work.


    I understand void pointer is pointer with no associated data type, which allows it to hold address of any type and can be typecasted to any type.

    In example code below, I see &ptrVar being casted to void*.

    QUESTION: Why is the (void*) cast necessary? I removed the void* cast and seems like the program still outputs the same result.

    Code:
    #include <stdio.h>
    
    int main()
    {
        int intVar = 10;
        int *ptrVar = &intVar;
    
    
        printf("ptrVar address: %p\n", (void*)&ptrVar);     // Output the address
        printf("value pointed to: %d\n", *ptrVar);          // Value at the address pointed
    
    
        return 0;
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    printf(3): formatted output conversion - Linux man page
    Because printf expects %p arguments to be explicitly void*

    Also, recall that printf is prototyped like so.
    int printf(const char *format, ...);
    Any parameters which match the ... position are not automatically cast to the correct type (like they would be with an actual prototype declaration), but are instead just promoted using the default promotion rules.
    Which means you need to be a little more specific.


    > QUESTION: Why is the (void*) cast necessary? I removed the void* cast and seems like the program still outputs the same result.
    It probably will, on most machines.
    Because most machines have the same pointer representation for all pointer types.
    But not all of them -> Question 5.17
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can`t cast float* to void* pointers
    By heatblazer in forum C Programming
    Replies: 3
    Last Post: 07-24-2015, 04:01 PM
  2. Replies: 3
    Last Post: 06-23-2010, 06:50 AM
  3. checking cast from void*
    By manustone in forum C++ Programming
    Replies: 12
    Last Post: 07-16-2009, 03:36 AM
  4. test void pointer before cast (instanceof)
    By jeanluca in forum C Programming
    Replies: 7
    Last Post: 05-29-2009, 04:26 AM
  5. type cast a pointer to void
    By rc7j in forum C++ Programming
    Replies: 1
    Last Post: 02-13-2002, 12:03 PM

Tags for this Thread