If you have ever found yourself puzzled by pointers, don't worry; you are not alone because pointers might sound tricky. But fear not! In this post, we are going to explore the basics of handling pointers in C through a simple and easy-to-follow program which shows how to handle pointers in C language.
Step by Step logic of the given program:
1. First declare integer pointer variable a, declare integer variable z assign z=10.
2. Print value of z and address of z using &z.
3. After that assign a with address of z using:
a=&z;
4. Print address of pointer a using %p. It prints the address of z because we already stored address of z in variable a.
5. After that print content of pointer a using *a it will print value of z=10.
6. After that assign z=30.
7. Print address of a using %p it will print address of z as it is. After that print content of pointer a using *a it will print changed value of z that means it will print 30.
8. After that assign value 5 to the pointer variable *a. Then print address of z and print value of z it will print value 5 because a contain the address of z.
Program to Show Working of Pointers:
#include<stdio.h>
int main()
{
int* a;
int z;
z=10;
printf("How works pointer and how to handle pointers-C program:\n\n");
printf("Value of z = %d\n",z);
printf("Address of z = %p\n",&z);
a=&z;
//Now, a is assigned with the address of z.
printf("\nNow a is assigned with the address of z:\n");
printf("Address of pointer a = %p\n",a);
printf("content of pointer a = %d\n\n",*a);
z=30;//now value of z is 30
printf("Now, The value of z assigned to 30:\n");
printf("Address of pointer a = %p\n",a);
printf(" Content of pointer a = %d\n\n",*a);
*a=5;
printf("Now, pointer variable a is assigned the value 5\n");
printf("Address of z = %p\n",&z);
/*here, a contain the address of z, so *a changed the value of z (now z=7)*/
printf("Value of z = %d",z);
return 0;
}
Above program shows the following output:
No comments:
Post a Comment
If you have any doubts, please discuss here...👇