Thread: how to dereference a void pointer

  1. #1
    Registered User
    Join Date
    Nov 2019
    Posts
    40

    how to dereference a void pointer

    A void pointer can hold address of any type

    if the pointer know the address of another variable, then we can change the value store in that address by pointer dereference

    In a code ptr hold the address of variable a

    how to modify value of a ?


    Code:
    #include<stdio.h>
    
    int main()
    {
        int a = 10;
    
    
        void *ptr = &a;
    
    
        printf("%d", *(int *)ptr);
    	
    	*ptr = 12;
    	 
    	printf("%d", *(int *)ptr);
    
    
        return 0;
    }
    error invalid use of void expression

  2. #2
    Registered User
    Join Date
    Sep 2020
    Posts
    425
    You need to case the "vold *" to a "something *" so the compiler knows what sort of data you are accessing (e.g. char, short, int, long, float double, a structure...)

    Code:
    *((int *)ptr) = 12;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. pointer dereference
    By leo2008 in forum C Programming
    Replies: 2
    Last Post: 04-13-2021, 11:30 PM
  2. dereference a pointer in a function
    By royalts in forum C Programming
    Replies: 8
    Last Post: 02-26-2015, 02:57 AM
  3. Replies: 3
    Last Post: 10-18-2011, 11:15 PM
  4. Pointer dereference
    By taurus in forum C Programming
    Replies: 1
    Last Post: 11-09-2008, 07:41 AM
  5. Dereference pointer to void pointer to member
    By phil in forum C Programming
    Replies: 5
    Last Post: 04-20-2005, 11:54 AM

Tags for this Thread