Home » C programs » C pointer programs

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?
Submitted by IncludeHelp, on November 14, 2018

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

Program:

#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 





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.