Codeforwin

void pointer or generic pointer in C – use and arithmetic

Quick links.

  • Dereference void pointer

void pointer arithmetic

  • Example program

Pointer is a variable pointing at a memory location of specific type . Type defines many important properties related to the pointer. Such as valid memory addresses it can point, pointer arithmetic, etc.

As per C programming semantics, you must specify pointer type during its declaration. Also, it is illegal to point pointer of one type to object of another type. For example, int pointer cannot point to a float variable.

Type specific pointers are beneficial in different ways. However, in programming there happens situation when you need to go typeless. For example, suppose you are required to design a function that can accept any type value as argument, process data and return results. For such situation, you need a pointer that must work with all types.

What is a void pointer?

A void pointer is a special pointer that can point to object of any type. A void pointer is typeless pointer also known as generic pointer . void pointer is an approach towards generic functions and generic programming in C.

Note: Writing programs without being constrained by data type is known as generic programming. A generic function is a special function that focuses on logic without confining to data type. For example, logic to insert values in array is common for all types and hence can be transformed to generic function.

Syntax to declare void pointer

Example to declare void pointer, how to dereference a void pointer.

Dereferencing is the process of retrieving data from memory location pointed by a pointer. It converts block of raw memory bytes to a meaningful data (data is meaningful if type is associated).

While dereferencing a void pointer, the C compiler does not have any clue about type of value pointed by the void pointer. Hence, dereferencing a void pointer is illegal in C. But, a pointer will become useless if you cannot dereference it back.

To dereference a void pointer you must typecast it to a valid pointer type.

Example to dereference a void pointer

void pointer arithmetic is illegal in C programming, due to the absence of type. However, some compiler supports void pointer arithmetic by assuming it as a char pointer.

To perform pointer arithmetic on void pointer you must first typecast to other type.

Example of void pointer arithmetic

Example program to use void pointer.

Write a C function to accept an array and print its elements . The function must accept array of different types.

cppreference.com

Pointer declaration.

Pointer is a type of an object that refers to a function or an object of another type, possibly adding qualifiers. Pointer may also refer to nothing, which is indicated by the special null pointer value.

[ edit ] Syntax

In the declaration grammar of a pointer declaration, the type-specifier sequence designates the pointed-to type (which may be function or object type and may be incomplete), and the declarator has the form:

where declarator may be the identifier that names the pointer being declared, including another pointer declarator (which would indicate a pointer to a pointer):

The qualifiers that appear between * and the identifier (or other nested declarator) qualify the type of the pointer that is being declared:

The attr-spec-seq (C23) is an optional list of attributes , applied to the declared pointer.

[ edit ] Explanation

Pointers are used for indirection, which is a ubiquitous programming technique; they can be used to implement pass-by-reference semantics, to access objects with dynamic storage duration , to implement "optional" types (using the null pointer value), aggregation relationship between structs, callbacks (using pointers to functions), generic interfaces (using pointers to void), and much more.

[ edit ] Pointers to objects

A pointer to object can be initialized with the result of the address-of operator applied to an expression of object type (which may be incomplete):

Pointers may appear as operands to the indirection operator (unary * ), which returns the lvalue identifying the pointed-to object:

Pointers to objects of struct and union type may also appear as the left-hand operands of the member access through pointer operator -> .

Because of the array-to-pointer implicit conversion, pointer to the first element of an array can be initialized with an expression of array type:

Certain addition, subtraction , compound assignment , increment, and decrement operators are defined for pointers to elements of arrays.

Comparison operators are defined for pointers to objects in some situations: two pointers that represent the same address compare equal, two null pointer values compare equal, pointers to elements of the same array compare the same as the array indexes of those elements, and pointers to struct members compare in order of declaration of those members.

Many implementations also provide strict total ordering of pointers of random origin, e.g. if they are implemented as addresses within continuous ("flat") virtual address space.

[ edit ] Pointers to functions

A pointer to function can be initialized with an address of a function. Because of the function-to-pointer conversion, the address-of operator is optional:

Unlike functions, pointers to functions are objects and thus can be stored in arrays, copied, assigned, passed to other functions as arguments, etc.

A pointer to function can be used on the left-hand side of the function call operator ; this invokes the pointed-to function:

Dereferencing a function pointer yields the function designator for the pointed-to function:

Equality comparison operators are defined for pointers to functions (they compare equal if pointing to the same function).

Because compatibility of function types ignores top-level qualifiers of the function parameters, pointers to functions whose parameters only differ in their top-level qualifiers are interchangeable:

[ edit ] Pointers to void

Pointer to object of any type can be implicitly converted to pointer to void (optionally const or volatile -qualified), and vice versa:

Pointers to void are used to pass objects of unknown type, which is common in generic interfaces: malloc returns void * , qsort expects a user-provided callback that accepts two const void * arguments. pthread_create expects a user-provided callback that accepts and returns void * . In all cases, it is the caller's responsibility to convert the pointer to the correct type before use.

[ edit ] Null pointers

Pointers of every type have a special value known as null pointer value of that type. A pointer whose value is null does not point to an object or a function (dereferencing a null pointer is undefined behavior), and compares equal to all pointers of the same type whose value is also null .

To initialize a pointer to null or to assign the null value to an existing pointer, a null pointer constant ( NULL , or any other integer constant with the value zero) may be used. static initialization also initializes pointers to their null values.

Null pointers can indicate the absence of an object or can be used to indicate other types of error conditions. In general, a function that receives a pointer argument almost always needs to check if the value is null and handle that case differently (for example, free does nothing when a null pointer is passed).

[ edit ] Notes

Although any pointer to object can be cast to pointer to object of a different type, dereferencing a pointer to the type different from the declared type of the object is almost always undefined behavior. See strict aliasing for details.

lvalue expressions of array type, when used in most contexts, undergo an implicit conversion to the pointer to the first element of the array. See array for details.

Pointers to char are often used to represent strings . To represent a valid byte string, a pointer must be pointing at a char that is an element of an array of char, and there must be a char with the value zero at some index greater or equal to the index of the element referenced by the pointer.

[ edit ] References

  • C17 standard (ISO/IEC 9899:2018):
  • 6.7.6.1 Pointer declarators (p: 93-94)
  • C11 standard (ISO/IEC 9899:2011):
  • 6.7.6.1 Pointer declarators (p: 130)
  • C99 standard (ISO/IEC 9899:1999):
  • 6.7.5.1 Pointer declarators (p: 115-116)
  • C89/C90 standard (ISO/IEC 9899:1990):
  • 3.5.4.1 Pointer declarators

[ edit ] See also

  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 15 June 2021, at 08:34.
  • This page has been accessed 68,822 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

C Programming Tutorial

  • Void Pointers in C

Last updated on July 27, 2020

We have learned in chapter Pointer Basics in C that if a pointer is of type pointer to int or (int *) then it can hold the address of the variable of type int only. It would be incorrect, if we assign an address of a float variable to a pointer of type pointer to int . But void pointer is an exception to this rule. A void pointer can point to a variable of any data type. Here is the syntax of void pointer.

Syntax: void *vp;

Let's take an example:

Here vp is a void pointer, so you can assign the address of any type of variable to it.

A void pointer can point to a variable of any data type and void pointer can be assigned to a pointer of any type.

Dereferencing a void Pointer #

We can't just dereference a void pointer using indirection ( * ) operator. For example:

It simply doesn't work that way!. Before you dereference a void pointer it must be typecasted to appropriate pointer type. Let me show you what I mean.

For example: In the above snippet void pointer vp is pointing to the address of integer variable a. So in this case vp is acting as a pointer to int or (int *) . Hence the proper typecast in this case is (int*) .

Now the type of vptr temporarily changes from void pointer to pointer to int or (int*) , and we already know how to dereference a pointer to int , just precede it with indirection operator ( * )

Note: typecasting changes type of vp temporarily until the evaluation of the expression, everywhere else in the program vp is still a void pointer.

The following program demonstrates how to dereference a void pointer.

Expected Output:

Pointer Arithmetic in Void Pointers #

Another important point I want to mention is about pointer arithmetic with void pointer. Before you apply pointer arithmetic in void pointers make sure to provide a proper typecast first otherwise you may get unexcepted results.

Consider the following example:

Here we have assigned the name of the array one_d to the void pointer vp . Since the base type of one_d is a pointer to int or (int*) , the void pointer vp is acting like a pointer to int or (int*) . So the proper typecast is (int*) .

The following program demonstrates pointer arithmetic in void pointers.

The void pointers are used extensively in dynamic memory allocation which we will discuss next.

Load Comments

  • Intro to C Programming
  • Installing Code Blocks
  • Creating and Running The First C Program
  • Basic Elements of a C Program
  • Keywords and Identifiers
  • Data Types in C
  • Constants in C
  • Variables in C
  • Input and Output in C
  • Formatted Input and Output in C
  • Arithmetic Operators in C
  • Operator Precedence and Associativity in C
  • Assignment Operator in C
  • Increment and Decrement Operators in C
  • Relational Operators in C
  • Logical Operators in C
  • Conditional Operator, Comma operator and sizeof() operator in C
  • Implicit Type Conversion in C
  • Explicit Type Conversion in C
  • if-else statements in C
  • The while loop in C
  • The do while loop in C
  • The for loop in C
  • The Infinite Loop in C
  • The break and continue statement in C
  • The Switch statement in C
  • Function basics in C
  • The return statement in C
  • Actual and Formal arguments in C
  • Local, Global and Static variables in C
  • Recursive Function in C
  • One dimensional Array in C
  • One Dimensional Array and Function in C
  • Two Dimensional Array in C
  • Pointer Basics in C
  • Pointer Arithmetic in C
  • Pointers and 1-D arrays
  • Pointers and 2-D arrays
  • Call by Value and Call by Reference in C
  • Returning more than one value from function in C
  • Returning a Pointer from a Function in C
  • Passing 1-D Array to a Function in C
  • Passing 2-D Array to a Function in C
  • Array of Pointers in C
  • The malloc() Function in C
  • The calloc() Function in C
  • The realloc() Function in C
  • String Basics in C
  • The strlen() Function in C
  • The strcmp() Function in C
  • The strcpy() Function in C
  • The strcat() Function in C
  • Character Array and Character Pointer in C
  • Array of Strings in C
  • Array of Pointers to Strings in C
  • The sprintf() Function in C
  • The sscanf() Function in C
  • Structure Basics in C
  • Array of Structures in C
  • Array as Member of Structure in C
  • Nested Structures in C
  • Pointer to a Structure in C
  • Pointers as Structure Member in C
  • Structures and Functions in C
  • Union Basics in C
  • typedef statement in C
  • Basics of File Handling in C
  • fputc() Function in C
  • fgetc() Function in C
  • fputs() Function in C
  • fgets() Function in C
  • fprintf() Function in C
  • fscanf() Function in C
  • fwrite() Function in C
  • fread() Function in C

Recent Posts

  • Machine Learning Experts You Should Be Following Online
  • 4 Ways to Prepare for the AP Computer Science A Exam
  • Finance Assignment Online Help for the Busy and Tired Students: Get Help from Experts
  • Top 9 Machine Learning Algorithms for Data Scientists
  • Data Science Learning Path or Steps to become a data scientist Final
  • Enable Edit Button in Shutter In Linux Mint 19 and Ubuntu 18.04
  • Python 3 time module
  • Pygments Tutorial
  • How to use Virtualenv?
  • Installing MySQL (Windows, Linux and Mac)
  • What is if __name__ == '__main__' in Python ?
  • Installing GoAccess (A Real-time web log analyzer)
  • Installing Isso

C Programming Void Pointer

Switch to English

  • Introduction

Table of Contents

Understanding Void Pointers

Uses of void pointers, working with void pointers, common mistakes with void pointers, tips and tricks.

  • A void pointer, also known as a generic pointer, is a special type of pointer that can be pointed to any data type's objects, be it a built-in or user-defined data type. The void pointer in C is declared using the keyword 'void'. For example:
  • However, a void pointer cannot be dereferenced directly. This means that you cannot directly fetch the value pointed by a void pointer. It must first be explicitly typecasted to another pointer type before dereferencing.
  • Void pointers are widely used in C programming for their flexibility. They can point to any data type, making them very versatile. In particular, void pointers are commonly used in function parameters and return types when we need a function to handle different data types.
  • Let's look at how to use void pointers with an example. Here we'll demonstrate a void pointer pointing to different data types:
  • Notice how before dereferencing the void pointer, we typecast it to the appropriate data type.
  • Not typecasting before dereferencing: As mentioned earlier, a void pointer cannot be directly dereferenced. If you try to do so, the compiler will throw an error. Always remember to typecast the void pointer to the appropriate data type before dereferencing.
  • Wrong typecasting: When you typecast a void pointer, ensure that you cast it to the correct type. If you cast it to the wrong type and then dereference it, you will get incorrect and unexpected results.
  • Using void pointers with arithmetic operations: Pointer arithmetic is not allowed on void pointers. For example, incrementing a void pointer would make no sense, as the compiler wouldn't know how many bytes to increment by.
  • Always typecast: It's always better to be explicit with your typecasts when working with void pointers. This will not only help prevent errors, but also make your code clearer and easier to understand.
  • Use void pointers sparingly: While void pointers provide flexibility, they should be used sparingly. Overuse of void pointers can lead to code that is hard to understand and maintain.
  • Be careful with pointer arithmetic: Remember, void pointers do not support pointer arithmetic. Always ensure that you're performing arithmetic operations on pointers of the correct type.
  • Getting started with C Language
  • Best C Programming Courses
  • Awesome Book
  • Awesome Community
  • Awesome Tutorial
  • Awesome YouTube
  • — character classification & conversion
  • Aliasing and effective type
  • Command-line arguments
  • Common C programming idioms and developer practices
  • Common pitfalls
  • Compilation
  • Compound Literals
  • Constraints
  • Create and include header files
  • Declaration vs Definition
  • Declarations
  • Enumerations
  • Error handling
  • Files and I/O streams
  • Formatted Input/Output
  • Function Parameters
  • Function Pointers
  • Generic selection
  • Identifier Scope
  • Implementation-defined behaviour
  • Implicit and Explicit Conversions
  • Initialization
  • Inline assembly
  • Interprocess Communication (IPC)
  • Iteration Statements/Loops: for, while, do-while
  • Jump Statements
  • Linked lists
  • Literals for numbers, characters and strings
  • Memory management
  • Multi-Character Character Sequence
  • Multithreading
  • Pass 2D-arrays to functions
  • Introduction
  • Address-of Operator ( & )
  • Common errors
  • Const Pointers
  • Dereferencing a Pointer
  • Dereferencing a Pointer to a struct
  • Function pointers
  • Initializing Pointers
  • Pointer Arithmetic
  • Pointer to Pointer
  • Polymorphic behaviour with void pointers
  • Same Asterisk, Different Meanings
  • void* pointers as arguments and return values to standard functions
  • Preprocessor and Macros
  • Random Number Generation
  • Selection Statements
  • Sequence points
  • Side Effects
  • Signal handling
  • Standard Math
  • Storage Classes
  • Structure Padding and Packing
  • Testing frameworks
  • Threads (native)
  • Type Qualifiers
  • Undefined behavior
  • Variable arguments

C Language Pointers void* pointers as arguments and return values to standard functions

Fastest entity framework extensions.

void* is a catch all type for pointers to object types. An example of this in use is with the malloc function, which is declared as

The pointer-to-void return type means that it is possible to assign the return value from malloc to a pointer to any other type of object:

It is generally considered good practice to not explicitly cast the values into and out of void pointers. In specific case of malloc() this is because with an explicit cast, the compiler may otherwise assume, but not warn about, an incorrect return type for malloc() , if you forget to include stdlib.h . It is also a case of using the correct behavior of void pointers to better conform to the DRY (don't repeat yourself) principle; compare the above to the following, wherein the following code contains several needless additional places where a typo could cause issues:

Similarly, functions such as

have their arguments specified as void * because the address of any object, regardless of the type, can be passed in. Here also, a call should not use a cast

Got any C Language Question?

pdf

  • Advertise with us
  • Cookie Policy
  • Privacy Policy

Get monthly updates about new articles, cheatsheets, and tricks.

Void Pointer In C | Referencing, Dereferencing & More (+Examples)

Shivani Goyal

Table of content: 

What is a void pointer in c, declaring and initializing void pointer in c with example, how does the void pointer work in c, common use cases of void pointer in c, size of the void pointer in c, referencing & dereferencing the void pointers in c, arithmetic operation on void pointers in c, why and when to use void pointers in c, limitations of void pointer in c, advantages of void pointer in c, key points to remember, frequently asked questions.

The pointer is one of the key components of the C programming language. A pointer can be used to hold information about other variables, functions, or even other pointers' memory addresses. Pointers in C programming allow several functional benefits, including low-level memory access and dynamic memory allocation. In this article, we will discuss a specific type of pointer, i.e., the void pointer in C, its uses, limitations, and more.

To begin with, let's get the basics of pointers right. A pointer is a derived data type that may be employed to store a memory location or the address of another C variable . The data stored at that memory location is accessed and modified via pointers.

Syntax Of Pointer

Pointer declarations follow a similar syntax to that of C variable declarations, but we use the (*) dereferencing operator instead.

data_type *ptr_variable;
  • Data_type: This represents the data type of the variable that the pointer will point to. Any legal C data type, including int, float, char, or even a specially defined data type, can be used.
  • The asterisk (*) indicates that the defined variable is a pointer. It is put before the name of the variable to indicate that it will hold the memory address of another variable.
  • The term ptr_variable identifies the pointer variable. Any legal name for an identifier is acceptable. It is advised to give the pointer a meaningful name that accurately describes its function.

Reverse A String In C | 10 Different Ways With Detailed Examples!

A void pointer is a unique type of pointer in the C language that may store the address of any data type . It is declared using the void keyword , which denotes the lack of a specified type attached to the pointer. When the precise data type is unknown or not required, void pointers offer a general method of working with pointers. Interview question

Some key features of void pointers in C programming are:

  • Lack of Type Information : Void pointers in C language are not connected with any type of information. They can point to any sort of object, including user-defined types, floats, characters, and integers. You cannot, however, immediately dereference or use pointer arithmetic on them since the type is unknown.
  • Typecasting : Before dereferencing, the data that a void pointer points to must undergo proper typecasting to the correct type to be used. The compiler may choose the appropriate size and interpretation of the data thanks to typecasting. Incorrect typecasting may result in runtime problems or behavior that is not defined.
  • Versatility : Void pointers in C can be very handy when you need a single pointer to dynamically handle a variety of data types. Without restricting their versatility, they are frequently employed in functions that must receive or return pointers of several types.

Void Pointer In C

Now that we know about the basics of what is a void pointer in C, let's see how to declare these pointers, followed by a proper C code example .

Syntax Of Void Pointer In C:

void *ptr_variable;
  • void: The void keyword indicates that the pointer does not have a specific data type associated with it. It's employed to declare a general-purpose pointer that may store addresses of any kind.

Code Example:

Value of intValue: 7 Value of floatValue: 3.14 Value of charValue: U

Explanation:

In this simple C program , we begin by including the <stdio.h> header file for essential input/ output operations.

  • Inside the main function, we declare and initialize three variables of different data types.
  • These are intValue (integer with the value 7), floatValue (floating-point number with the value 3.14), and charValue (character with the value 'U').
  • Next, we declare a void pointer ptr (i.e., void *ptr), which can hold the address of any data type.
  • As mentioned in the code comments , when we assign the addresses of the variables to the void pointers one by one.
  • We then use a printf() statement to display the variable's value to the console.
  • Inside the statement, we first typecast the void pointer to the integer pointer using the cast operator, i.e., (int *).
  • Then, we once again use the dereference operator (*) to access the value pointed to by ptr and print it to the console, i.e., *(int *)ptr.
  • We also use the %d format specifier inside the formatted string to indicate integer value and a newline escape sequence to shift the cursor to the next line.
  • We then reassign ptr with the value of the floatValue variable using the address-of operator (&). Then, we typecast the void pointer to a float pointer and print it to the console using the dereference operator.
  • Similarly, we assign the address of charValue to ptr , then typecast the pointer to the character pointer and print it to the console using printf() and dereferencing.
  • Finally, the main() function terminates with a return 0 statement, indicating no errors in execution. 

Time Complexity: O(1)

This example shows that we can access and print the values kept in each corresponding memory location by dereferencing the void pointer with the typecast. To ensure safe memory access and avoid type-related problems, consider that utilizing a void pointer needs careful treatment, including appropriate typecasting.

Note that although void pointers offer flexibility, they should be used with care. To prevent type-related mistakes and guarantee appropriate memory access, it is essential to ensure proper typecasting.

A void pointer in C can be declared and initialized in a variety of ways. We'll look at two typical methods, i.e., declaring a void pointer without initialization and declaring a void pointer with initialization.

Declaring A Void Pointer In C Without Initialization

This method involves merely declaring the pointer variable with the syntax void * type. Here, we do not assign any specific location to the pointer. This is why the process if referred to as defining a void pointer in C without initializing it. It is useful if we want to assign an address at a later time, as we did in the example before.

  • A void pointer that may hold the address of any data type is declared by the void pointer declaration.
  • The void pointer variable's name is ptr_variable.
  • Any legal name for an identifier is acceptable.

Take a look at the C code below, which shows how to declare a void pointer in C without initializing it in the same line. 

Code Example: :

Value of num: 10

In the sample C code -

  • We define the void pointer named ptr in the main() function after including the standard input/ output library. 
  • Then, we declare an integer type variable called num and initialize it with the value of 10.
  • Next, we use the reference operator (&) to assign the address of num to the pointer ptr.
  • After that, we use the printf() function to print the value of num. For this, we first typecast the void pointer to an integer pointer (int *)ptr to indicate that it points to an integer type data.
  • Then, we dereference the pointer , i.e., *(int *)ptr, to obtain the value stored at the memory location it points to and print it.
  • Lastly, the main() function closes with a return 0, indicating successful program execution to the operating system.

Time Complexity : 0(1)

Declaring A Void Pointer In C With Initialization

When defining a void pointer in C programs with initialization, the pointer variable must first be declared with the void keyword and assigned an initial value at the same time using the assignment operator . The initial value can be any variable's address, regardless of its data type, or NULL.

void *ptr_variable = NULL;
  • A void pointer may carry the address of any type of data thanks to the void * declaration.
  • The void pointer variable is referred to as ptr_variable.
  • The void pointer's initial value is set to null via the = NULL operator. The pointer should not point to any specific region in memory until a proper address has been assigned; thus, doing this is a good idea.

In the C code example-

  • We declare a void pointer called ptr and initialize it with NULL. Here, NULL is a special value representing that the pointer currently does not point to any valid memory location.
  • Then, we declare an integer variable, num , and initialize it with the value 10.
  • We then assign the address of the num variable to ptr using the address-of operator(&). Now, ptr points to the memory location where num is stored.
  • Next, we use a printf() statement to access the num variable using the pointer and print it to the console. 
  • In the statement, we first typecast the void pointer to an integer pointer, i.e., (int *)ptr to indicate that it points to an integer type data.
  • Then, we dereference the pointer to access the value stored at that memory location, i.e., *(int *)ptr.

Complexity:

  • Initializing and declaring a void pointer are straightforward procedures.
  • The actions carried out on the data the void pointer points to determine the complexity.
  • Dereferencing and typecasting void pointers might result in type-related errors if the wrong data type is assumed, which would add to the complexity.

In summary, void pointers in C offer a versatile approach to recording memory locations of any data type. They may be declared by both initializing to NULL and without initialization. When utilizing void pointers, care must be taken to guarantee appropriate typecasting and dereferencing because improper usage may result in undefinable behavior.

Array Of Pointers In C & Dereferencing With Detailed Examples

A void pointer in C is a special type of pointer that can hold the address of any data type but does not know the data type it points to. Here's a detailed description of how void pointers work in C:

Step 1: Declaration and Initialization

We first declare a void pointer in C using the void keyword, i.e., void *ptr. A void pointer doesn't know the size or data type of the variable it points to, so it cannot be directly dereferenced. We can also initialize the pointer to NULL (i.e., void *ptr = NULL) to indicate that it currently doesn't point to any valid memory address.

Step 2: Assignment

A void pointer can be assigned the address of variables of any data type, including basic data types (int, float, char), arrays , structs, or even function pointers. For this, we use the reference/ address-of operator (&). When you assign an address to a void pointer, the pointer stores the memory address and effectively forgets about the data type it points to.

Step 3: Typecasting

Before you can use a void pointer to access or manipulate the value it points to, you must first typecast the pointer it to the correct data type. Typecasting has to mostly be done explicitly by specifying the desired data type in parentheses before dereferencing the pointer.

For example, (int *)ptr for an integer, (float *)ptr for a float, (char *)ptr for a character, etc.

It is essential to ensure the void pointer is correctly typecasted to the appropriate data type; otherwise, accessing or manipulating the value could lead to undefined behavior.

Step 4: Dereferencing

After typecasting, you can dereference the void pointer using the indirection operator/ dereferencing operator (*) to access the value stored at the memory location it points to.

For example, if ptr points to an integer variable, you would dereference it as *(int *)ptr, or if it points to a character, you would dereference it as *(char *)ptr.

Unlike other pointers, a void pointer doesn't have a specific data type associated with it. This flexibility makes void pointers useful in various scenarios. Here are some common use cases of void pointers in C:

  • Generic Functions: Void pointers in C are often used in functions that handle different data types. For example, you might have a sorting function that can sort arrays of different data types by accepting a void pointer to the array and another void pointer to a comparison function.
void mySort(void *array, size_t elemSize, size_t arraySize, int (*compare)(const void *, const void *));
  • Dynamic Memory Allocation: Void pointers in C are frequently used in conjunction with dynamic memory allocation functions like malloc(), calloc(), and realloc(). These functions return a void pointer that can be typecasted to the desired data type.
int *intArray = (int*)malloc(5 * sizeof(int));
  • Parameter Passing in Thread Functions: When creating threads using a library like pthreads(), void pointers can be used to pass parameters to the thread function. The thread function can then cast the void pointer in C to the appropriate type.
void* threadFunction(void *arg);
  • File I/O: In functions related to file I/O, void pointers can be used for reading or writing data of different types.
FILE *fp = fopen("example.txt", "r"); void *buffer = malloc(100); fread(buffer, sizeof(char), 100, fp);
  • Memory Copying: Void pointers in C are useful when copying blocks of memory from one location to another, especially when the data type is not known beforehand.
void* myMemcpy(void *dest, const void *src, size_t n);

Void Pointer In C

In C, the size of a void pointer depends on the implementation. It varies depending on the underlying architecture and the particular compiler being used. The platform and the data model, such as 32-bit or 64-bit systems, often determine the size of a pointer.

  • The size of the void pointer on a 16-bit system is 2 bytes.
  • The size of the void pointer on a 32-bit system is 4 bytes.
  • The size of the void pointer on a 64-bit system is 8 bytes.

The sizeof() operator can be used to determine the size of a void pointer in C. Given below is the syntax for the same, followed by a code example.

Syntax For SizeOf Void Pointer In C:

sizeof(void *)
  • The sizeof() operator returns the operand's size in bytes. It is possible to use it to determine the size of different data types, including pointers.
  • A void pointer type is represented by the void keyword followed by an asterisk (*).
Size of void pointer: 8 bytes
  • Inside the main() function of the program, we use the sizeof() on a void pointer to calculate the size.
  • The expression sizeof(void *) yields a void pointer's size in bytes.
  • For size_t (the return type of sizeof ), we use the printf() function to print the size using the %zu format specifier.
  • The result displays the void pointer's size, which in this instance is 8 bytes. Depending on the platform and compiler being used, the precise size could change.

In order to operate with pointers in C, including void pointers, one must perform the fundamental procedures of referencing and dereferencing.

Referencing : Obtaining a variable's memory location and assigning it to a pointer is referred to as referencing. Referencing is accomplished using the address-of operator (&).

Void Pointer In C

To reference a variable and assign its address to a pointer, use the following syntax:

data_type *ptr_name; ptr_name = &variable_name;
  • The data_type refers to the type of data the pointer, whose name is given by ptr_name , is pointing to.
  • The variable_name indicates the name of the variable whose address is being assigned to the pointer using the reference operator (&) .

Dereferencing : Dereferencing a pointer refers to gaining access to the value kept at the memory address the pointer is pointing to. Dereferencing is done with the help of the dereference operator (*).

To dereference a pointer and access the value it points to, use the following syntax:

Here, the name of the pointer is given by ptr_name , and it is accessed using the dereference operator (*) .

Value of num using void pointer: 23
  • Inside the main() function of the program, we declare an integer variable named num that is initialized with the value 23.
  • We also declare a void pointer called ptr and then assign the address of the num variable to it.
  • Then, inside the printf() function, we explicitly typecast ptr to an integer pointer using cast operator, i.e., (int *) .
  • After that, we dereference the printer, i.e., *(int *)ptr , to access the value the void pointer points to.
  • The void pointer is used to read and display the value of num, which results in an output of 23.

Register Memory: Types, Functions & Differences Explained 

C does not provide arithmetic operations on void pointers. That is, pointer arithmetic is not specified for void pointers in C since they are not connected with a particular data type.

The size of the data type the pointer is pointing to determines how pointer arithmetic works in C. A void pointer cannot be meaningfully added to, subtracted from, incremented, or decremented since its size is unknown, which results in unpredictable behavior.

Answer: 0x7ffee19aa984
  • We first declare void pointer ptr in the main() function and then initialize the interger variable num with the value 10.
  • Next, we assign the void pointer ptr the address of num using the address-of operator ( & ).
  • After that, we try to conduct some arithmetic (arithmetic addition) by adding 1 to the void pointer ptr and assigning the outcome to another void pointer result .
  • The pointer's address is displayed by printing the value of the result using the %p format specifier.

Note- It's crucial to remember that this code generates behavior that is not defined . Since the output value of the result depends on the implementation , it cannot be utilized with confidence.

  • The conventions of pointer arithmetic are violated and broken when operations are performed on void pointers in C.
  • The void pointer in C has to be typecasted to a specified pointer type to specify the size of the data type it points to before performing legal pointer arithmetic.
  • After that, the typed pointer may be used for mathematical operations.

In conclusion, C prohibits the use of arithmetic operations on void pointers. Void pointers must be typecast to a specific pointer type before being used for arithmetic operations, mostly for general pointer storage.

Void pointers in C are employed when it's necessary to write generic C code that may operate on a variety of data types without being bound to a particular type. Here are several situations and justifications for using void pointers in C:

  • Generic Interfaces: The use of void pointers in C makes it possible to build APIs, data structures, and functions that can work with many data types. This is helpful if you want to create adaptable code that can work with different types of data without requiring numerous versions.
  • Memory Management: Void pointers in C can be utilized in situations when you need to dynamically allocate and deallocate memory for various kinds of data. Writing general memory management procedures that operate with any form of data is possible by utilizing void pointers.
  • Data Structures: Void pointers in C may be used to create data structures, such as linked lists or binary trees, that can handle and store many sorts of components. More flexible and reusable programming is now possible.
  • Callback Functions: When sending function pointers as parameters to other functions, callback functions frequently utilize void pointers. This enables the called function to call the callback function even when it isn't aware of the precise function signature or data types involved.

Void Pointer In C Example 1- Generic Printf() Function & Void Pointer To Access Variables

Integer value: 23 Float value: 3.14 Character value: M

In this example C program -

  • We start by defining a function called printValue to print the value of a variable whose address is passed to a void pointer, along with a character representing the data type.
  • For the case i (integer) , the function prints the integer value using printf and typecasts the void* pointer to an int*.
  • For the case f (float) , the function prints the float value with two decimal places using printf and typecasts the void* pointer to a float*.
  • For case c (character) , the function prints the character value using printf and typecasts the void* pointer to a char*.
  • If none of the specified cases match, the function prints "Invalid data type."
  • The break and continue statements ensure that the flow continues if the case is not met, and exits the switch statement once a case has been implemented. 
  • Then, in the main() function , we declare and initialize three variables (intValue, floatValue, and charValue) with different values.
  • Next, we call the printValue function three times with the addresses of these variables and their corresponding data type characters ('i', 'f', 'c').
  • This way we can access the variables stored in the void pointer and print it to the console.
  • The program returns 0 to the operating system, indicating successful execution.

Void Pointer In C Example 2- Generic Dynamic Memory Allocation 

Code Example: 

Value of intPtr: 23 Value of floatPtr: 3.14

We begin the example by including essential header files for dynamic memory allocation and deallocation, i.e., <stdlib.h> and <stdio.h> for input/ output operations.

  • We then define a function allocateMemory, which takes a size_t parameter, dynamically allocates memory using malloc based on the specified size, and returns a void* pointer.
  • Then, we define another function, deallocateMemory , that takes a void* pointer, representing the allocated memory, and frees it using the free function.
  • Inside the main() function , memory is then dynamically allocated for an integer (intPtr) and a float (floatPtr) using the allocateMemory function .
  • Next, we assign values (23 for intPtr and 3.14 for floatPtr) to the allocated memory locations using dereferencing.
  • We then print the values stored in the allocated memory to the console using the printf() function .
  • Lastly, we deallocate the memory allocated for both pointers using the deallocateMemory() function t o prevent memory leaks.
  • Finally, the program returns 0 to the operating system, indicating successful execution.

Void pointers in C give programmers freedom and genericity in writing concise and efficient programs. But they also have several restrictions. Here are some drawbacks of the void pointers in C:

  • No Type Safety: Since void pointers can point to any data type, they are not type-safe. This implies that type checking cannot be performed at compile time by the compiler, and therefore, incorrect use or typecasting of void pointers in C may result in runtime errors or unpredictable behavior .
  • Need for Explicit Typecasting: The use of a void pointer in C necessitates explicit typecasting in order to correctly access the data it links to. If the typecasting is done incorrectly, this adds a degree of complexity and the opportunity for mistakes.
  • No Pointer Arithmetic: Pointer arithmetic operations like addition, subtraction, and increment/decrement cannot be performed on void pointers. Pointer arithmetic is useless since it depends on the size of the data type, which is unknown for a void pointer in C.
  • Limited Compile-Time Checking: Errors related to memory access or type mismatch may not be caught at compile-time because void pointers in C can carry any address, even incorrect addresses. Debugging becomes more difficult because these mistakes might not be discovered until runtime.
  • Lack of Size Information: These pointers do not retain the size of the data they point to. Due to this, it may be challenging to calculate the amount of the data to carry out activities, such as copying or comparing data, that depend on size.
  • Increased Possibility of Glitch: The adaptability of void pointers in C raises the possibility of glitches and difficult-to-detect mistakes. Without the appropriate typecasting and checks, it is easier to introduce errors and inconsistencies into the code.

The following are the benefits of void pointers in C:

  • Flexibility and Generality: Void pointers give programmers a method to write code that isn't bound to any one data type and can handle a variety of data types. They increase the adaptability and reuse of code by enabling the development of functions, data structures, and APIs that can work with different forms of data.
  • Dynamic Memory Management: Void pointers in C are frequently employed in situations involving dynamic memory allocation functions. They enable the assignment and release of memory blocks of various sizes and kinds of data. When working with data structures that can contain elements of various kinds or when the extent of the allocated RAM is decided at runtime, this flexibility is very helpful.
  • Function Pointers and Callbacks: The void pointers in C are also employed when working with function pointers and constructing callback systems. They make it possible to build generic callback functions that can take multiple kinds of function pointers, giving you a means to dynamically handle diverse activities or events.
  • Compatibility with Outside Libraries: Void pointers in C make it easier for external libraries or APIs that use opaque types or have variable return types to communicate with each other. They act as a link between C code and libraries made in other languages by enabling the transfer of generic data to and from other functions.
  • Interfaces that are independent of data type: Void pointers in C make it possible to create interfaces that are independent of data type and may be utilized by a variety of modules or components. By separating the interface from specific implementation details, this abstraction supports modularity and encapsulation.
  • Effective Memory Allocation: Void pointers in C can be used to allocate memory blocks of various sizes, increasing the effectiveness and efficiency of memory allocation. They make it possible for memory allocation algorithms to be more flexible, particularly when working with a variety of data types or variable-sized structures.
  • Reduced Compilation Dependencies: Void pointers in C might minimize the compilation's reliance on certain data types. This might be advantageous when working with complicated or big codebases since it enables the decoupling of certain modules or functions from particular data types, lowering compile-time dependencies and accelerating build times.

The following are some significant one must remember when working with a void pointer in C:

  • Typeless Pointer : A void pointer can also be referred to as a typeless pointer in C. The fact that it can store the address of any data type enables generic programming.
  • Typecasting: Before dereferencing or executing operations on the data they point to, void pointers in C must be explicitly typecast to the correct data type. This is essential due to the compiler's lack of knowledge regarding a void pointer's underlying data type.
  • Lack of Size Information: These pointers do not retain the size of the data they point to. Because of this, it's crucial to explicitly handle the size when using these pointers in operations like copying or comparing data.
  • Passing Void Pointers as Function Arguments: The void pointers in C are frequently used as function pointers when sending generic data or objects to functions. As a result, functions may operate on several data types without requiring unique implementations for each type.
  • Pointer arithmetic: Void pointers in C cannot be used for arithmetic operations like addition, subtraction, increment, or decrement. Pointer arithmetic is useless for void pointers since they have an unknown size.
  • Handling of Invalid Memory Access: Given that a void pointer in C is capable of storing any address, including invalid or uninitialized addresses, it is crucial to take care of any issues that can occur while reading or changing the data referred to by a void pointer.
  • Type Safety Considerations: Void pointers cause a loss of type safety since they enable generic programming; hence, they should be avoided. To prevent such issues, it is essential to handle void pointers carefully, guarantee appropriate typecasting, and carry out the necessary runtime checks.
  • Portability: These pointers are portable across several systems and compilers because of the standardized behavior of void pointers in C. When working with void pointers, it's crucial to be aware of any unique platform or compiler restrictions.

Void pointers in C language are an effective tool for handling generic data and building flexible, reusable programs. They enable the creation of generic interfaces, data structures, and functions that can operate on a number of data types and are not constrained to a particular type. Void pointers are used to efficiently manage dynamic memory, interact with third-party libraries, and allocate memory.

However, it is essential to handle them cautiously since void pointers in C lack type safety and call for explicit typecasting. Proper usage is essential to preventing errors and erratic behaviors. Dereferencing, typecasting, and managing memory allocation and deallocation are all included. Knowing the advantages, limitations, and best practices of void pointers may help developers construct C programs that are more adaptive and versatile.

Q. What are void pointers and null pointers in C?

Void Pointer: A void pointer in C, denoted by the symbol void *, is a particular kind of pointer that may store the address of any type of data. It is a general-purpose pointer without a defined data type. The void pointer is largely used to achieve flexibility and generality in code, enabling the development of functions and data structures that are not restricted to a single data type and may operate on a variety of data types. When dereferencing or executing operations on the data it links to, explicit typecasting is necessary since the void pointer in C lacks type information.

Value of intValue: 42 Value of floatValue: 3.140000 Value of charValue: A

Null Pointer: A null pointer is a specific value that can be applied to a pointer variable to show that it does not point to any usable memory locations. It signifies the absence of a correct address. The literal constant NULL, which is commonly defined as (void *)0, is how the null pointer is represented in C. Null pointers are frequently employed to initialize pointers, check for faulty or uninitialized pointers, or signify the conclusion of specific data structures.

Output: ptr is a null pointer.

Q. What is pointer dereferencing in C?

In C, pointer dereferencing refers to accessing the value held at the memory address that the pointer is pointing to. The dereference operator (*) is used to do this. Dereferencing a pointer allows you to access or change the data kept at the memory address the pointer is pointing to.

Q. What is the void * pointer function ?

An operation that utilizes or returns a void pointer is referred to as a void * pointer function. The function may handle various data types with more flexibility as a result. By employing void pointers as function parameters or return types, such functions are capable of working with a variety of data types. The use of void pointers within functions, however, frequently necessitates explicit typecasting before dereferencing or executing actions on the data.

Q. What are dangling pointers in C?

D/inter: In the C programming language, a dangling pointer is a pointer that directs the user to an invalid or deallocated memory address. Usually, it happens when a pointer is released or when a function delivers a pointer to a local variable that exits the scope of the function. When dereferenced, dangling pointers may behave in an undefinable way.

Value at ptr: 10

Q. What is a double pointer in C?

A double pointer, usually referred to as a pointer to a pointer, is a specific kind of pointer that stores the address of another pointer variable. Dynamic data structures like pointer arrays , linked lists, and multi-dimensional arrays may be created and modified using this technique. In situations when pointers are sent by reference or when working with dynamically allocated memory, double pointers offer an additional degree of indirection.

Value at ptr: 42

Q. What is an indirection operator in C?

The indirection operator, indicated by placing a pointer variable name right after it with no space in between, is a tool that helps fetch the value stored in the memory location pointed by a pointer variable.

Value of 'num' : 42

Code explanation: In this example, ptr is a pointer variable pointing to the memory location of the integer variable num . The *ptr expression, using the indirection operator (*), allows us to retrieve and print the value stored at that memory location, which is 42 in this case.

Q. What is the difference between void and void pointer?

The void keyword can be used both to create void pointers in C as well as to create other elements like functions that are of void type. The table below lists the difference between the void keyword and the void pointer in C. 

Q. What is the difference between a specific pointer and a void pointer in C?

Void pointers (void*) and specific pointers (pointers to a specific data type) have distinct characteristics and use cases in C programming.

A void pointer in C (void*) is a general-purpose pointer with no specific data type associated with it. It can be used to store the address of any data type.

  • The flexibility of void pointers allows for generic programming, especially in situations where the data type is not known beforehand or needs to be determined dynamically at runtime.
  • However, using void pointers requires careful typecasting when dereferencing to ensure proper interpretation of the data.

A specific pointer , on the other hand, is a pointer that is explicitly defined to point to a particular data type. For example, a pointer declared as int* is meant to store the address of an integer variable, and it can only be used to point to integer values.

  • Specific pointers provide type safety and allow the compiler to perform type-checking during compilation, catching potential errors at an earlier stage.
  • This specificity comes at the cost of reduced flexibility compared to void pointers.

Enjoyed reading about void pointers in C? Here are a few other curated pieces on important programming fundamentals you must know:

  • Logical Operators In C Explained (Types With Examples)
  • Control Statements In C | The Beginner's Guide (With Examples)
  • Comma Operator In C | Code Examples For Both Separator & Operator
  • Jump Statement In C | Types, Best Practices & More (+Examples)
  • Tokens In C | A Complete Guide To 7 Token Types (With Examples)

Shivani Goyal

I am an economics graduate using my qualifications and life skills to observe & absorb what life has to offer. A strong believer in 'Don't die before you are dead' philosophy, at Unstop I am producing content that resonates and enables you to be #Unstoppable. When I don't have to be presentable for the job, I'd be elbow deep in paint/ pencil residue, immersed in a good read or socializing in the flesh.

CreaTech 2024

to our newsletter

Blogs you need to hog!

Reverse A String In C | 10 Different Ways With Detailed Examples!

Reverse A String In C | 10 Different Ways With Detailed Examples!

c void pointer assignment

Array Of Pointers In C & Dereferencing With Detailed Examples

A professional computer programmer and coder working with language processors

Language Processors: Definition, Types, Functions & Differences 

c void pointer assignment

Register Memory: Types, Functions & Differences Explained 

c void pointer assignment

Home Calendar Assignments Admin Resources

Void and Function Pointers

Void pointers, function pointers, a brief tutorial on function pointers.

Next: Assigning Function Pointers , Up: Function Pointers   [ Contents ][ Index ]

22.5.1 Declaring Function Pointers

The declaration of a function pointer variable (or structure field) looks almost like a function declaration, except it has an additional ‘ * ’ just before the variable name. Proper nesting requires a pair of parentheses around the two of them. For instance, int (*a) (); says, “Declare a as a pointer such that *a is an int -returning function.”

Contrast these three declarations:

The possible argument types of the function pointed to are the same as in a function declaration. You can write a prototype that specifies all the argument types:

or one that specifies some and leaves the rest unspecified:

or one that says there are no arguments:

You can also write a non-prototype declaration that says nothing about the argument types:

For example, here’s a declaration for a variable that should point to some arithmetic function that operates on two double s:

Structure fields, union alternatives, and array elements can be function pointers; so can parameter variables. The function pointer declaration construct can also be combined with other operators allowed in declarations. For instance,

declares foo as a pointer to a function that returns type int ** , and

declares foo as an array of 30 pointers to functions that return type int ** .

declares foo as a pointer to a pointer to a function that returns type int ** .

Next: Pointer Comparison , Previous: Dereferencing Null or Invalid Pointers , Up: Pointers   [ Contents ][ Index ]

14.8 Void Pointers

The peculiar type void * , a pointer whose target type is void , is used often in C. It represents a pointer to we-don’t-say-what. Thus,

declares a function numbered_slot_pointer that takes an integer parameter and returns a pointer, but we don’t say what type of data it points to.

The functions for dynamic memory allocation (see Dynamic Memory Allocation ) use type void * to refer to blocks of memory, regardless of what sort of data the program stores in those blocks.

With type void * , you can pass the pointer around and test whether it is null. However, dereferencing it gives a void value that can’t be used (see The Void Type ). To dereference the pointer, first convert it to some other pointer type.

Assignments convert void * automatically to any other pointer type, if the left operand has a pointer type; for instance,

Passing an argument of type void * for a parameter that has a pointer type also converts. For example, supposing the function hack is declared to require type float * for its argument, this will convert the null pointer to that type.

You can also convert to another pointer type with an explicit cast (see Explicit Type Conversion ), like this:

Here is an example which decides at run time which pointer type to convert to:

The expression *(int *)ptr means to convert ptr to type int * , then dereference it.

  • Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

  • Computer Fundamental
  • Computer Memory
  • DBMS Tutorial
  • Operating System
  • Computer Networking
  • C Programming
  • C++ Programming
  • Java Programming
  • C# Programming
  • SQL Tutorial
  • Management Tutorial
  • Computer Graphics
  • Compiler Design
  • Style Sheet
  • JavaScript Tutorial
  • Html Tutorial
  • Wordpress Tutorial
  • Python Tutorial
  • PHP Tutorial
  • JSP Tutorial
  • AngularJS Tutorial
  • Data Structures
  • E Commerce Tutorial
  • Visual Basic
  • Structs2 Tutorial
  • Digital Electronics
  • Internet Terms
  • Servlet Tutorial
  • Software Engineering
  • Interviews Questions
  • Basic Terms
  • Troubleshooting

Header Right

How to pointer assignment and initialization in c.

By Dinesh Thakur

When we declare a pointer, it does not point to any specific variable. We must initialize it to point to the desired variable. This is achieved by assigning the address of that variable to the pointer variable, as shown below.

int a = 10;

pa = &a; /* pointer variable pa now points to variable a */

In this example, the first line declares an int variable named a and initializes it to 10. The second line declares a pointer pa of type pointer to int. Finally, the address of variable a is assigned to pa.Now pa is said to point to variable a.

We can also initialize a pointer when it is declared using the format given below.

type * ptr_var = init_expr ;

where init_expr is an expression that specifies the address of a previously defined variable of appropriate type or it can be NULL, a constant defined in the <stdio.h> header file.

Consider the example given below.

float x = 0.5;

float *px = &x;

int *p = NULL;

The second line declares a pointer variable px of type float * and initializes it with the address of variable x declared in the first line. Thus, pointer px now points to variable x. The third line declares pointer variable p of type int * and initializes it to NULL. Thus, pointer p does not point to any variable and it is an error to dereference such a pointer.

Note that a character pointer can be initialized using a character string constant as in

char *msg = “Hello, world!”;

Here, the C compiler allocates the required memory for the string constant (14 characters, in the above example, including the null terminator), stores the string constant in this memory and then assigns the initial address of this memory to pointer msg,as iliustrated in Fig.

pointer variable pointing to a string constant

The C language also permits initialization of more that one pointer variable in a single statement using the format shown below.

type *ptr_var1 = init_expr1, *ptr_var2 = init_expr2, … ;

It is also possible to mix the declaration and initialization of ordinary variables and pointers. However, we should avoid it to maintain program readability.

Example of Pointer Assignment and Initialization

char a= ‘A’;

char *pa = &a;

printf(“The address of character variable a: %p\n”, pa);

printf(“The address of pointer variable pa : %p\n”, &pa);

printf(“The value pointed by pointer variable pa: %c\n”, *pa);

Here, pa is a character pointer variable that is initialized with the address of character variable a defined in the first line. Thus, pa points to variable a. The first two printf statements print the address of variables a and pa using the %p (p for pointer) conversion. The last printf statement prints the value of a using the pointer variable pa. When the program containing this code is executed in Code::Blocks, the output is displayed as shown below. ·

The address of character variable a: 0022FF1F

The address of pointer variable pa : 0022FF18

The value pointed by pointer variable pa: A

Note that the addresses displayed in the output will usually be different depending on other variables declared in the program and the compiler/IDE used.

Another example is given below in which pointers are initialized with the addresses of variables of incompatible type.

char c = ‘Z’;

int i = 10;

float f = 1.1;

char *pcl = &i, *pc2 = &f;

int *pil = &c, *pi2 = &f;

float *pfl = &c, *pf2 = &i;

printf(“Character: %c %c\n”, *pcl, *pc2);

printf(“Integer : %d %d\n”, *pil, *pi2);

printf (“Float : %f %f\n”, =pfl, *pf2);

Note that the character pointer variables pcl and pc2 are initialized with the addresses of the int and float variables, respectively. Similarly, the int and float pointer variables are also initialized with addresses of variables of incompatible type. When the program containing this code is compiled in Code::Blocks, the compiler reports six warning messages (initialization from incompatible pointer type), one for each incompatible pointer initialization.

It is not a good idea to ignore such warnings associated with pointers. Although, the program executes in the presence of these warnings, it displays wrong results as shown below.

Integer : 90 1066192077

Float : 0.000000 0.000000

You’ll also like:

  • Write A C++ Program To Signify Importance Of Assignment (=) And Shorthand Assignment (+=) Operator.
  • Write C++ Example to illustrate two dimensional array implemented as pointer to a pointer.
  • Two-Dimensional Arrays Using a Pointer to Pointer
  • Declaration and Initialization of Pointers in C
  • Initialization of Two Dimensional Arrays Java

Dinesh Thakur

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.

For any type of query or something that you think is missing, please feel free to Contact us .

Basic Course

  • Database System
  • Management System
  • Electronic Commerce

Programming

  • Structured Query (SQL)
  • Java Servlet

World Wide Web

  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • C++ Data Types
  • C++ Input/Output
  • C++ Pointers
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
  • weak_ptr in C++
  • Pointer to an Array in C++
  • Application of Pointer in C++
  • NULL Pointer in C++
  • Assignment Operators In C++
  • User-Defined Data Types In C
  • C++ Global Variables
  • Mutex in C++
  • String Tokenization in C
  • C++ Program For Sentinel Linear Search
  • Nested Inline Namespaces In C++20
  • std::shared_mutex in C++
  • C++20 std::basic_syncbuf
  • Bitmask in C++
  • Difference Between Constant and Literals
  • String Functions In C++
  • Nested Try Blocks in C++
  • Concurrency in C++
  • Condition Variables in C++ Multithreading

void Pointer in C++

In C++, a void pointer is a pointer that is declared using the ‘ void ‘ keyword (void*). It is different from regular pointers it is used to point to data of no specified data type. It can point to any type of data so it is also called a “ Generic Pointer “. 

Syntax of Void Pointer in C++

As the type of data the void pointer is pointing to is unknown, we cannot dereference a void pointer.

Example of Void Pointer in C++

The below example demonstrates the declaration and use of void pointer in C++.

Application of Void Pointer in C++

1. generic coding.

The concept of a generic pointer means a pointer that can be used to point to data of any data type. This is helpful in situations where you need a single pointer that can handle different data types dynamically.

Let’s see an example for this, let’s first declare variables of different types (int, double, char). then declare a void pointer named “generic pointer”. We use the void pointer to point to each of the variables in succession with the help of typecasting.

Below is a program in which an int type pointer is declared and we try to point the value of a float datatype using it. Let’s See what happens.

Explanation: The above program gives an error the reason is int type pointer ptr is declared and we are trying to store the memory address of a float data type into an int pointer, which gives an error. But if we declare void pointer it allows us to change their data type. So, declare ptr as a void pointer and the program will not give any error. The below example demonstrates the same.

Explanation : In the above Code, We declared a void pointer as the variable name “ptr” which acts as a generic pointer or void pointer. This pointer stores multiple datatype addresses like int, char and float. We Typecasted the void pointer to any data type (float, char, int). Hence Void Pointer allows us to change the addresses for different memory addresses of different data types.

2. Dynamic Memory Allocation

Dynamic memory allocation is performed in C++, when the size of memory needed is not known at compile time then we perform Dynamic memory Allocation using operators like new or malloc. Void pointers can be used to allocate memory for any data type. In C++, “new” keyword is used for dynamic memory allocation which returns a pointer to the allocated memory. After allocating memory, We need perform type casting to use the allocated memory with a specific data type.

The below program demonstrate the use of void pointer to dynamically allocate memory for any data type.

3. Callback Functions

Functions that are passed as arguments to other functions are called callback functions. In case we need to handle multiple data types, the void pointer can be used as a void pointer provides us the flexibility to handle different data types. Callback functions can be defined to accept a void pointer as a parameter, enabling them to handle different types of data. This approach simplifies the code because this approach maintains different data types in a single callback.

The below program demonstrates the use of the void function to pass a void pointer as a parameter in a callback function.

Advantages of void Pointer in C++

The void pointer have the following major applications:

  • The use of void pointers can help reduce redundant code by allowing a single piece of code to handle multiple data types.
  • Void pointer allows abstraction of specific types in favor of a more general interface. This is common in scenarios like polymorphic containers or callback systems.
  • A void pointer can be declared to deal with polymorphism.
  • Void pointers can enhance platform independence where the sizes and representations of data types may vary across different architectures.

In conclusion, void pointers in C++ offer flexibility and versatility in certain programming scenarios, but this demands careful consideration. Modern C++ offers safer alternatives, like smart pointers for memory management.

Please Login to comment...

author

  • cpp-pointer
  • Geeks Premier League 2023
  • Geeks Premier League
  • 10 Best Free Social Media Management and Marketing Apps for Android - 2024
  • 10 Best Customer Database Software of 2024
  • How to Delete Whatsapp Business Account?
  • Discord vs Zoom: Select The Efficienct One for Virtual Meetings?
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

COMMENTS

  1. when assigning to void pointer in C

    There is only assignment of address to a pointer. For this assignment to work l.h.s and r.h.s have to be compatible i.e: of the same data type. A void pointer is a special pointer which can point to any type, you can typecast a void pointer back to the exact type it points to. In C you can do this without any explicit cast because it is a ...

  2. void Pointer in C

    Advantages of Void Pointers in C. Following are the advantages of void pointers. malloc () and calloc () return void * type and this allows these functions to be used to allocate memory of any data type (just because of void *). void pointers in C are used to implement generic functions in C. For example, compare function which is used in qsort ().

  3. Concept of void pointer in C programming

    When a pointer variable is declared using keyword void - it becomes a general purpose pointer variable. Address of any variable of any data type (char, int, float etc.)can be assigned to a void pointer variable. main() {. int *p; void *vp; vp=p;

  4. Void Pointers (GNU C Language Manual)

    The peculiar type void *, a pointer whose target type is void, is used often in C. It represents a pointer to we-don't-say-what. Thus, declares a function numbered_slot_pointer that takes an integer parameter and returns a pointer, but we don't say what type of data it points to. The functions for dynamic memory allocation (see Dynamic ...

  5. C Pointers

    The Void pointers in C are the pointers of type void. It means that they do not have any associated data type. ... Assignment of pointers of the same type. C // C program to illustrate Pointer Arithmetic #include <stdio.h> int main {// Declare an array int v [3] ...

  6. void pointer or generic pointer in C

    A void pointer is typeless pointer also known as generic pointer. void pointer is an approach towards generic functions and generic programming in C. Note: Writing programs without being constrained by data type is known as generic programming. A generic function is a special function that focuses on logic without confining to data type.

  7. Pointer declaration

    Pointers to functions. A pointer to function can be initialized with an address of a function. Because of the function-to-pointer conversion, the address-of operator is optional: void f (int);void(* pf1 )(int)=& f;void(* pf2 )(int)= f;// same as &f. Unlike functions, pointers to functions are objects and thus can be stored in arrays, copied ...

  8. Void Pointers in C

    Void Pointers in C. Last updated on July 27, 2020 We have learned in chapter Pointer Basics in C that if a pointer is of type pointer to int or (int *) then it can hold the address of the variable of type int only. It would be incorrect, if we assign an address of a float variable to a pointer of type pointer to int. But void pointer

  9. Dangling, Void , Null and Wild Pointers in C

    Output. 2355224 Void Pointer in C. Void pointer is a specific pointer type - void * - a pointer that points to some data location in storage, which doesn't have any specific type. Void refers to the type. Basically, the type of data that it points to can be any. Any pointer type is convertible to a void pointer hence it can point to any value.

  10. Mastering Void Pointers in C Programming

    A void pointer, also known as a generic pointer, is a special type of pointer that can be pointed to any data type's objects, be it a built-in or user-defined data type. The void pointer in C is declared using the keyword 'void'. For example: void *ptr; // ptr is a void pointer. However, a void pointer cannot be dereferenced directly.

  11. C Language Tutorial => void* pointers as arguments and return

    The pointer-to-void return type means that it is possible to assign the return value from malloc to a pointer to any other type of object: int* vector = malloc(10 * sizeof *vector); It is generally considered good practice to not explicitly cast the values into and out of void pointers. In specific case of malloc () this is because with an ...

  12. Void Pointer In C Explained In Detail With Code Examples // Unstop

    Output: Value of num: 10. Explanation: In the sample C code-. We define the void pointer named ptr in the main() function after including the standard input/ output library.; Then, we declare an integer type variable called num and initialize it with the value of 10.; Next, we use the reference operator (&) to assign the address of num to the pointer ptr.; After that, we use the printf ...

  13. void Pointers in C

    The assignment operator (=) may be used on pointers of the same type. However, if the types of pointers (types of variables to which they point) are not same then we will have to do type casting of one of these to the type of the other to use assignment operator.However, the void pointer (void * ) can represent any pointer type. Thus, any type of pointer may be assigned to a void pointer.

  14. Tufts: CS 40 Void and Function Pointers

    Void pointers Preamble: There are 3 unrelated meanings in C for the keyword void: As function return type: this function has no return value. ... The supplemental chapter to Hanson linked from the III assignment has a great description of this and has a nice table comparing the two strategies. Function Pointers

  15. c

    Depending on the compiler settings (you may be compiling as C++ and not as C), you may need to cast the pointers to a char pointer: memcpy((char *) copy, (const char *) ptr, sizeOfBlock); Note: The parameter of the function should be const char *ptr, to make sure you don't change the contents of ptr by mistake. edited Dec 19, 2015 at 22:58.

  16. Declaring Function Pointers (GNU C Language Manual)

    The declaration of a function pointer variable (or structure field) looks almost like a function declaration, except it has an additional ' * ' just before the variable name. Proper nesting requires a pair of parentheses around the two of them. For instance, int (*a) (); says, "Declare a as a pointer such that *a is an int -returning ...

  17. Void Pointers (GNU C Language Manual)

    The peculiar type void *, a pointer whose target type is void, is used often in C. It represents a pointer to we-don't-say-what. Thus, declares a function numbered_slot_pointer that takes an integer parameter and returns a pointer, but we don't say what type of data it points to. The functions for dynamic memory allocation (see Dynamic ...

  18. How to Pointer Assignment and Initialization in C

    This is achieved by assigning the address of that variable to the pointer variable, as shown below. int a = 10; int *pa; pa = &a; /* pointer variable pa now points to variable a */. In this example, the first line declares an int variable named a and initializes it to 10. The second line declares a pointer pa of type pointer to int.

  19. c

    pVoid is assigned the value NULL.This is because the expression (void*)0 is defined as a null pointer constant.. Section 6.3.2.3p3 of the C standard states:. An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant.If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is ...

  20. PDF CS 3214, Spring 2024 Malloc Lab: Writing a 64-bit Dynamic Storage

    The memlib.c package provides the memory system for your dynamic memory allocator. You can invoke the following functions in memlib.c: • void *mem sbrk(int incr): Expands the heap by incrbytes, where incris a positive non-zero integer and returns a generic pointer to the first byte of the newly allocated heap area.

  21. void Pointer in C++

    void Pointer in C++. In C++, a void pointer is a pointer that is declared using the ' void ' keyword (void*). It is different from regular pointers it is used to point to data of no specified data type. It can point to any type of data so it is also called a " Generic Pointer ".

  22. C++ pointer assignment

    Now we have two variables x and y: int *p = &x; int *q = &y; There are declared another two variables, pointer p which points to variable x and contains its address and pointer q which points to variable y and contains its address: x = 35; y = 46; Here you assign values to the variables, this is clear: p = q;