Accessing Array Elements with a Void Pointer in C


In C programming, a void pointer, also known as a generic pointer, is a pointer that can point to any type of data. It is declared using the void * data type.

A void pointer does not have a specific data type associated with it, and it cannot be dereferenced directly. Instead, it must be cast to a specific data type before it can be dereferenced and used to access the data it points to.

Here is an example of how a void pointer can be used in C:

  • The program starts by including the standard input-output library, stdio.h, which is used to input and output data.
  • In the main function, an integer array a is declared and initialized with the values 10, 20, 30, 40, and 50. A void pointer variable p is also declared.
  • The void pointer variable p is then assigned the memory address of the first element of the array a. Since a void pointer is a generic pointer, it cannot be dereferenced directly, so it must be cast to a specific data type before it can be dereferenced and used to access the data it points to.
  • In the next line, the program uses the printf function to print the value stored at the memory location pointed to by p, which is the value of the first element of the array a. The pointer is casted to int pointer using (int *)before dereferencing.

This program demonstrates how to use a void pointer to access elements of an array. It also demonstrates how to use type casting to access the data stored at the memory location pointed to by the void pointer.

Source Code

//Generic Pointer or Void Pointers
#include<stdio.h>
int main()
{
    int a[]={10,20,30,40,50};
    void *p;
    p=a;
    //printf("\n *p : %d",*p);
    printf("\n *p : %d",*(int *)p);
    return 0;
}
 
 
 
To download raw file Click Here

Output

 *p : 10

List of Programs


Sample Programs


Switch Case in C


Conditional Operators in C


Goto Statement in C


While Loop Example Programs


Looping Statements in C

For Loop Example Programs


Array Examples in C

One Dimensional Array


Two Dimensional Array in C


String Example Programs in C


Functions Example Programs in C