Write a C program to declare, initialize and demonstrate the use of pointer. How to access value and address of a variable using pointer in C programming.
Required knowledge:
Accessing memory location of any variable using & operator
We know that address of operator gives the address of any variable. We can prefix the address of operator (&) with the variable name to get the memory location of a variable like this:
/*C program to print value and address of each variable
*uisng address of (&) operator */.
int main()
{
int x = 10;
char y = 'C'
float fl = 10.50f
/*Printing the value and address of each variables*/
printf("Value of x = %d and address of x = %p\n" , x, &x);
printf("Value of y = %c and address of y = %p\n" , y, &y);
printf("Value of fl = %.2f and address of fl = %p\n" , fl, &fl);
return 0;
}
Note: You can use format specifier %p, %x, and %u to print the address in hexadecimal format.
Output
Value of x = 10 and address of x = 0x1ff1
Value of y = C and address of y = 0x2ff2
Value of fl = 10.50 and address of fl = 0x3ff3
Accessing value of variable using pointer
To display the value of var using pointer, the unary operator * is used which returns the value of variable var whose address is stored by the pointer (i.e. *ptr). Let's have a look at the below example.
Use of pointer | welcome2protec.com |
/*C program to to print value and address of var using pointer*/
#include <stdio.h>
int main(){
int var = 10; /* Declaration of normal variable */
int *ptr; /* Declaration of pointer variable */
/* storing address of var in pointer variable
* (or can say initialization of pointer)*/
ptr = &var;
/*Printing value and address of var using & operator*/
printf("Value of var = %d and Address of var = %x\n", var, &var);
/*Printing value and address of var using pointer*/
printf("Value of var = %d and Address of var = %x\n", *ptr, ptr);
/* printing the address of pointer variable i.e. ptr */
printf("Address pointer ptr variable: %x\n", &ptr );
/* Let's change the value of var using pointer */
*ptr = 20;
printf("Value of var has now been changed to %d\n", *ptr );
return 0;
}
Output
Value of var = 10 and Address of var = 0xbffd8b3c4c
Value of var = 10 and Address of var = 0xbffd8b3c4c
Address of ptr = 0xbffd8b3c50
Value of var has now been changed to 20
0 Comments:
Post a Comment
Please don't enter any spam link in the comment box.