Programmer Coding

Void pointer in C Language

Void pointer in C

A void pointer in C is a pointer that is not associated with any data type. It points to the address of the stored data, that is, it points to the address of the variable. It is also called the universal index. In C, the malloc() and calloc() functions return an empty * or public pointer. 1) Pointer arithmetic cannot be done using null pointers due to their size. 1)     It cannot be used as denial.

Here’s a simple algorithm to demonstrate the use of void pointers in C:

  1. Declaration: Declare a void pointer variable.
  2. Allocation: Allocate memory for an object of a specific data type.
  3. Assignment: Assign the address of the allocated memory to the void pointer.
  4. Access: Use typecasting to access the data stored at the memory location pointed to by the void pointer.

 Example

#include <stdio.h>
#include <stdlib.h>

int main() {
// Step 1: Declaration
void *ptr;

// Step 2: Allocation
int num = 10;
ptr = malloc(sizeof(int)); // Allocate memory for an integer

if (ptr == NULL) {
printf(“Memory allocation failed.\n”);
return 1;
}

// Step 3: Assignment
*(int *)ptr = num; // Store the value of ‘num’ at the memory location pointed to by ‘ptr’

// Step 4: Access
int value = *(int *)ptr; // Typecasting to access the value stored at ‘ptr’
printf(“Value stored at ptr: %d\n”, value);

// Step 5: Deallocation (optional)
free(ptr); // Free the dynamically allocated memory

return 0;
}

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top