void Pointer in C - GeeksforGeeks (2025)

Skip to content

  • Courses
    • DSA Courses
    • Programming Languages
  • Tutorials
    • Python
    • Java
    • Programming Languages
    • Interview Corner
    • Computer Science Subjects
    • DevOps and Linux
    • Software Testing
    • Databases
    • Android
    • Excel
    • Mathematics
  • DSA
    • Practice
    • Company Wise SDE Sheets
    • Puzzles
  • Data Science
    • Data Science Packages
    • Data Visualization
    • Data Analysis
  • Web Tech
    • Web Development Using Python
    • Cheat Sheets
  • C
  • C Basics
  • C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Arrays
  • C Strings
  • C Pointers
  • C Preprocessors
  • C File Handling
  • C Programs
  • C Cheatsheet
  • C Interview Questions
  • C MCQ
  • C++

Open In App

Next Article:void Pointer in C++

Last Updated : 11 Oct, 2024

Summarize

Comments

Improve

Suggest changes

Like Article

Like

Report

A void pointer is a pointer that has no associated data type with it. A void pointer can hold an address of any type and can be typecasted to any type.

Example of Void Pointer in C

C
// C Program to demonstrate that a void pointer// can hold the address of any type-castable type#include <stdio.h>int main(){ int a = 10; char b = 'x'; // void pointer holds address of int 'a' void* p = &a; // void pointer holds address of char 'b' p = &b;}


Time Complexity: O(1)
Auxiliary Space: O(1)

If you’re looking to master pointers, including how they work with data structures, the C Programming Course Online with Data Structures covers pointers extensively with practical use cases.

Properties of Void Pointers

1. void pointers cannot be dereferenced.

Example

The following program doesn’t compile.

C
// C Program to demonstrate that a void pointer// cannot be dereferenced#include <stdio.h>int main(){ int a = 10; void* ptr = &a; printf("%d", *ptr); return 0;}


Output

Compiler Error: 'void*' is not a pointer-to-object type

The below program demonstrates the usage of a void pointer to store the address of an integer variable and the void pointer is typecasted to an integer pointer and then dereferenced to access the value. The following program compiles and runs fine.

C
// C program to dereference the void// pointer to access the value#include <stdio.h>int main(){ int a = 10; void* ptr = &a; // The void pointer 'ptr' is cast to an integer pointer // using '(int*)ptr' Then, the value is dereferenced // with `*(int*)ptr` to get the value at that memory // location printf("%d", *(int*)ptr); return 0;}

Output

10

Time Complexity: O(1)
Auxiliary Space: O(1)

2. The C standard doesn’t allow pointer arithmetic with void pointers. However, in GNU C it is allowed by considering the size of the void as 1.

Example

The below C program demonstrates the usage of a void pointer to perform pointer arithmetic and access a specific memory location. The following program compiles and runs fine in gcc.

C
// C program to demonstrate the usage// of a void pointer to perform pointer// arithmetic and access a specific memory location#include <stdio.h>int main(){ // Declare and initialize an integer array 'a' with two // elements int a[2] = { 1, 2 }; // Declare a void pointer and assign the address of // array 'a' to it void* ptr = &a; // Increment the pointer by the size of an integer ptr = ptr + sizeof(int); // The void pointer 'ptr' is cast to an integer // pointer using '(int*)ptr' Then, the value is // dereferenced with `*(int*)ptr` to get the value at // that memory location printf("%d", *(int*)ptr); return 0;}

Output

2

Time Complexity: O(1)
Auxiliary Space: O(1)

Note: The above program may not work in other compilers.

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().
  • void pointers used along with Function pointers of type void (*)(void) point to the functions that take any arguments and return any value.
  • void pointers are mainly used in the implementation of data structures such as linked lists, trees, and queues i.e. dynamic data structures.
  • void pointers are also commonly used for typecasting.


Next Article

void Pointer in C++

kartik

void Pointer in C - GeeksforGeeks (5)

Improve

Article Tags :

  • C Language
  • C Basics
  • C-Pointers
  • cpp-pointer

Similar Reads

  • void Pointer in C A void pointer is a pointer that has no associated data type with it. A void pointer can hold an address of any type and can be typecasted to any type. Example of Void Pointer in C[GFGTABS] C // C Program to demonstrate that a void pointer // can hold the address of any type-castable type #include 3 min read
  • 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++void* ptr_name; 7 min read
  • C File Pointer A file pointer is a variable that is used to refer to an opened file in a C program. The file pointer is actually a structure that stores the file data such as the file name, its location, mode, and the current position in the file. It is used in almost all the file operations in C such as opening, 3 min read
  • C Pointers A pointer is a variable that stores the memory address of another variable. Instead of holding a direct value, it holds the address where the value is stored in memory. There are 2 important operators that we will use in pointers concepts i.e. Dereferencing operator(*) used to declare pointer variab 10 min read
  • C++ Pointers Pointers are symbolic representations of addresses. They enable programs to simulate call-by-reference as well as to create and manipulate dynamic data structures. Iterating over elements in arrays or other data structures is one of the main use of pointers. The address of the variable you're workin 9 min read
  • printf in C In C language, printf() function is used to print formatted output to the standard output stdout (which is generally the console screen). The printf function is the most used output function in C and it allows formatting the output in many ways. Example: [GFGTABS] C #include <stdio.h> int main 6 min read
  • Function Pointer in C In C, a function pointer is a type of pointer that stores the address of a function, allowing functions to be passed as arguments and invoked dynamically. It is useful in techniques such as callback functions, event-driven programs, and polymorphism (a concept where a function or operator behaves di 6 min read
  • Function Pointer in C++ Prerequisites: Pointers in C++Function in C++ Pointers are symbolic representations of addresses. They enable programs to simulate call-by-reference as well as to create and manipulate dynamic data structures. Iterating over elements in arrays or other data structures is one of the main use of point 4 min read
  • snprintf() in C In C, snprintf() function is a standard library function that is used to print the specified string till a specified length in the specified format. It is defined in the <stdio.h> header file. In this article, we will learn about snprintf() function in C and how to use it in our program. Synta 3 min read
  • Dangling, Void , Null and Wild Pointers in C In C programming pointers are used to manipulate memory addresses, to store the address of some variable or memory location. But certain situations and characteristics related to pointers become challenging in terms of memory safety and program behavior these include Dangling (when pointing to deall 6 min read

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy

void Pointer in C - GeeksforGeeks (7)

'); // $('.spinner-loading-overlay').show(); let script = document.createElement('script'); script.src = 'https://assets.geeksforgeeks.org/v2/editor-prod/static/js/bundle.min.js'; script.defer = true document.head.appendChild(script); script.onload = function() { suggestionModalEditor() //to add editor in suggestion modal if(loginData && loginData.premiumConsent){ personalNoteEditor() //to load editor in personal note } } script.onerror = function() { if($('.editorError').length){ $('.editorError').remove(); } var messageDiv = $('').text('Editor not loaded due to some issues'); $('#suggestion-section-textarea').append(messageDiv); $('.suggest-bottom-btn').hide(); $('.suggestion-section').hide(); editorLoaded = false; } }); //suggestion modal editor function suggestionModalEditor(){ // editor params const params = { data: undefined, plugins: ["BOLD", "ITALIC", "UNDERLINE", "PREBLOCK"], } // loading editor try { suggestEditorInstance = new GFGEditorWrapper("suggestion-section-textarea", params, { appNode: true }) suggestEditorInstance._createEditor("") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } //personal note editor function personalNoteEditor(){ // editor params const params = { data: undefined, plugins: ["UNDO", "REDO", "BOLD", "ITALIC", "NUMBERED_LIST", "BULLET_LIST", "TEXTALIGNMENTDROPDOWN"], placeholderText: "Description to be......", } // loading editor try { let notesEditorInstance = new GFGEditorWrapper("pn-editor", params, { appNode: true }) notesEditorInstance._createEditor(loginData&&loginData.user_personal_note?loginData.user_personal_note:"") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; }} var lockedCasesHtml = `You can suggest the changes for now and it will be under 'My Suggestions' Tab on Write.

You will be notified via email once the article is available for improvement. Thank you for your valuable feedback!`; var badgesRequiredHtml = `It seems that you do not meet the eligibility criteria to create improvements for this article, as only users who have earned specific badges are permitted to do so.

However, you can still create improvements through the Pick for Improvement section.`; jQuery('.improve-header-sec-child').on('click', function(){ jQuery('.improve-modal--overlay').hide(); $('.improve-modal--suggestion').hide(); jQuery('#suggestion-modal-alert').hide(); }); $('.suggest-change_wrapper, .locked-status--impove-modal .improve-bottom-btn').on('click',function(){ // when suggest changes option is clicked $('.ContentEditable__root').text(""); $('.suggest-bottom-btn').html("Suggest changes"); $('.thank-you-message').css("display","none"); $('.improve-modal--improvement').hide(); $('.improve-modal--suggestion').show(); $('#suggestion-section-textarea').show(); jQuery('#suggestion-modal-alert').hide(); if(suggestEditorInstance !== null){ suggestEditorInstance.setEditorValue(""); } $('.suggestion-section').css('display', 'block'); jQuery('.suggest-bottom-btn').css("display","block"); }); $('.create-improvement_wrapper').on('click',function(){ // when create improvement option clicked then improvement reason will be shown if(loginData && loginData.isLoggedIn) { $('body').append('

'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status) }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ } $('.improve-modal--improvement').show(); }); const showErrorMessage = (result,statusCode) => { if(!result) return; $('.spinner-loading-overlay:eq(0)').remove(); if(statusCode == 403) { $('.improve-modal--improve-content.error-message').html(result.message); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); return; } } function suggestionCall() { var editorValue = suggestEditorInstance.getValue(); var suggest_val = $(".ContentEditable__root").find("[data-lexical-text='true']").map(function() { return $(this).text().trim(); }).get().join(' '); suggest_val = suggest_val.replace(/\s+/g, ' ').trim(); var array_String= suggest_val.split(" ") //array of words var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(editorValue.length <= 2000){ var payload = { "gfg_post_id" : `${post_id}`, "suggestion" : `${editorValue}`, } if(!loginData || !loginData.isLoggedIn) // User is not logged in payload["g-recaptcha-token"] = gCaptchaToken jQuery.ajax({ type:'post', url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/", xhrFields: { withCredentials: true }, crossDomain: true, contentType:'application/json', data: JSON.stringify(payload), success:function(data) { if(!loginData || !loginData.isLoggedIn) { grecaptcha.reset(); } jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('.suggest-bottom-btn').css("display","none"); $('#suggestion-section-textarea').hide() $('.thank-you-message').css('display', 'flex'); $('.suggestion-section').css('display', 'none'); jQuery('#suggestion-modal-alert').hide(); }, error:function(data) { if(!loginData || !loginData.isLoggedIn) { grecaptcha.reset(); } jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Something went wrong."); jQuery('#suggestion-modal-alert').show(); error_msg = true; } }); } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Minimum 4 Words and Maximum Words limit is 1000."); jQuery('#suggestion-modal-alert').show(); jQuery('.ContentEditable__root').focus(); error_msg = true; } } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Enter atleast four words !"); jQuery('#suggestion-modal-alert').show(); jQuery('.ContentEditable__root').focus(); error_msg = true; } if(error_msg){ setTimeout(() => { jQuery('.ContentEditable__root').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append(''); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // script for grecaptcha loaded in loginmodal.html and call function to set the token setGoogleRecaptcha(); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append(''); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status); }, }); });

"For an ad-free experience and exclusive features, subscribe to our Premium Plan!"

Continue without supporting

void Pointer in C - GeeksforGeeks (2025)
Top Articles
Latest Posts
Recommended Articles
Article information

Author: Velia Krajcik

Last Updated:

Views: 5757

Rating: 4.3 / 5 (74 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Velia Krajcik

Birthday: 1996-07-27

Address: 520 Balistreri Mount, South Armand, OR 60528

Phone: +466880739437

Job: Future Retail Associate

Hobby: Polo, Scouting, Worldbuilding, Cosplaying, Photography, Rowing, Nordic skating

Introduction: My name is Velia Krajcik, I am a handsome, clean, lucky, gleaming, magnificent, proud, glorious person who loves writing and wants to share my knowledge and understanding with you.