Code Snippets C/C++ Code Snippets

C program to demonstrate example of void pointer.

By: IncludeHelp, On 11 OCT 2016

In this program we will learn how to assign address of various types of variables in void pointer and how we can access the value of other type of variables using void pointer?

In this example there is a voidPointer which is being assigned with the address of int, float , char type variables a, b, c.

And while accessing (printing) the value of a, b, c, we are changing the type of void pointer with int*, float*, char* (called type casting).

C program (Code Snippet) - Assigning the Address of another type variables and Accessing the values

Let’s consider the following example:

/*C program to demonstrate example of void pointer*/

#include <stdio.h>
int main(){
	void *voidPointer;
	int a=10;;
	float b=1.234f;
	char c='x';
	
	voidPointer=&a;
	printf("value of a: %d\n",*(int*)voidPointer);
	
	voidPointer=&b;
	printf("value of b: %f\n",*(float*)voidPointer);
	
	voidPointer=&c;
	printf("value of c: %c\n",*(char*)voidPointer);
	
	return 0;	
}

Output

    value of a: 10
    value of b: 1.234000
    value of c: x




Copyright © 2024 www.includehelp.com. All rights reserved.