Modify value stored in other variable using pointer in C

Here, we are going to learn how to modify the value of a variable using pointer in C language?
By IncludeHelp Last updated : March 10, 2024

Prerequisite

An Example of Null pointer in C

As we know that a pointer contains the address of another variable and by dereferencing the pointer (using asterisk (*) operator), we can access the value to that variable and we can also update that value.

Steps

  • Declare a pointer of same type
  • Initialize the pointer with the other (normal variable whose value we have to modify) variable's address
  • Update the value

C program to modify value stored in other variable using pointer

#include <stdio.h>

int main(void) {
	int num = 10;
	//declaring and initializing the pointer
	int *ptr = &num;

	printf("value of num: %d\n", num);
	printf("value of num: (using pointer): %d\n", *ptr);

	//updating the value
	*ptr = 20;

	printf("value of num: %d\n", num);
	printf("value of num (using pointer): %d\n", *ptr);

	return 0;
}

Output

value of num: 10 
value of num: (using pointer): 10
value of num: 20 
value of num (using pointer): 20 

C Pointer Programs »


Comments and Discussions!

Load comments ↻






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