Program to Change the Value Stored at the address in C

Introduction

In this post, I am going to write a program to change the value which is stored at the address in c programming. Here, we can use the pointer variable. Whenever we deal with addresses, then we can use the pointer.

Also Read: Switch Case in C Program to Calculate Area of Circle and Triangle

Pointer variable stores the address of another variable. See the following program.

Program to Change the Value Stored at the address in C

#include<stdio.h>
#include<stdlib.h>
int main()
{
    int a=5;
    int *ptr;
    ptr=&a;
    printf("The value of a is %d\n",a);
    *ptr=10;
    printf("The value of a is %d",a);
}

Output

The value of a is 5
The value of a is 10

As you can see the above output, we have changed the value of a from 5 to 10. We have not used the statement like a=10 to change the value of a. See the detailed explanation of the program.

Also Read: Program in C to Replace Capital C with Capital S in a File

Explanation

int a=5;

We have declared the variable a as an integer and initialized it with the value 5.

int *ptr;

Here, we have declared a pointer variable ptr which will store the value of the variable a.

ptr=&a;

Here, we are assigning the address of the variable to the pointer variable ptr. Suppose, the address of the variable a is 1000. Then, the value of ptr is 100.

printf(“The value of a is %d\n”,a);

Here, we are displaying the original value of a.

*ptr=10;

Now, this is our main statement. Here, *ptr is pointing to the address which is stored in the pointer variable ptr. We know the value of ptr is 1000 which is nothing but the address of the variable a. So, we are replacing the value a to 10using this statement.

Also Read: C Language Program to Count the Number of Lowercase Letters in a Text File

The statement a=10 and *ptr=10 are the same. But, our main aim is to write a program to change the value stored at the address in c programming.

After this, we will display the value of a which is 10 this time.

I hope you have understood this program. If you have any difficulty or any feedback, then please feel free to contact me.

Thank you.

Important Programs

  1. C Program to Remove White Spaces and Comments from a File
  2. Perfect Number in C Programming using All Loops
  3. Reverse a Number in C
  4. Switch Case in C Programming
  5. C Program to Count the Characters in the String Except Space

Leave a Comment