Introduction
A pointer is a variable whose value is also an address. As described earlier, each variable has two attributes: address and value. A variable can take any value specified by its data type. For example, if the variable i is of the integer type, it can take any value permitted in the range specified by the integer data type. A pointer to an integer is a variable that can store the address of that integer.
Program
#includemain () { int i; //A int * ia; //B i = 10; //C ia = &i; //D printf (" The address of i is %8u \n", ia); //E printf (" The value at that location is %d\n", i); //F printf (" The value at that location is %d\n", *ia); //G *ia = 50; //H printf ("The value of i is %d\n", i); //I }
Explanation
-
The program declares two variables, so memory is allocated for two variables. i is of the type of int, and ia can store the address of an integer, so it is a pointer to an integer.
-
The memory allocation is as follows:
-
i gets the address 1000, and ia gets address 4000.
-
When you execute i = 10, 10 is written at location 1000.
-
When you execute ia = &i then the address and value are assigned to i, thus i has the address of 4000 and value is 1000.
-
You can print the value of i by using the format %au because addresses are usually in the format unsigned long, as given in statement E.
-
Statement F prints the value of i, (at the location 1000).
-
Alternatively, you can print the value at location 1000 using statement G. *ia means you are printing the value at the location specified by ia. Since i has the value for 1000, it will print the value at location 1000.
-
When you execute *ia = 50, which is specified by statement H, the value 50 is written at the location by ia. Since ia specifies the location 1000, the value at the location 1000 is written as 50.
-
Since i also has the location 1000, the value of i gets changed automatically from 10 to 50, which is confirmed from the printf statement written at position i.
Points to Remember
-
Pointers give a facility to access the value of a variable indirectly.
-
You can define a pointer by including a* before the name of the variable.
-
You can get the address where a variable is stored by using &.
No comments:
Post a Comment