Accessing the value of a variable using pointer in C

Here, we are going to learn how to access the value of a variable using pointer in C programming language?
Submitted by IncludeHelp, on November 01, 2018

As we know that a pointer is a special type of variable that is used to store the memory address of another variable. A normal variable contains the value of any type like int, char, float etc, while a pointer variable contains the memory address of another variable.

Here, we are going to learn how can we access the value of another variable using the pointer variable?

Steps:

  1. Declare a normal variable, assign the value
  2. Declare a pointer variable with the same type as the normal variable
  3. Initialize the pointer variable with the address of normal variable
  4. Access the value of the variable by using asterisk (*) - it is known as dereference operator

Example:

Here, we have declared a normal integer variable num and pointer variable ptr, ptr is being initialized with the address of num and finally getting the value of num using pointer variable ptr.

#include <stdio.h>

int main(void)
{	
	//normal variable
	int num = 100;	
	
	//pointer variable
	int *ptr;		
	
	//pointer initialization
	ptr = &num;		
	
	//pritning the value 
	printf("value of num = %d\n", *ptr);

	return 0;
}

Output

value of num = 100

Related Tutorials



Comments and Discussions!

Load comments ↻





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