Professional Documents
Culture Documents
Pointers
Pointers
Pointers are what the word literally means. They point to something. That something
can be the location in the memory to a variable, an array or a structure. In object
oriented programming languages like C++, they can point to objects. For a day to day
example, a pointer can point to any file in your computer. Have you noticed that when
you cut-paste a (big)file from one drive to another, it takes some time. But when you do
the same within a drive, it happens instantaneously. It is because when you cut-paste to
a different drive, the contents(actual file) has to be moved, but when it is done within
the drive, the pointer to that file is simply redirected to the new location. Similarly
deleting a file simply means deleting the pointer to the memory location of that file. So
to completely erase data from a hard drive tech guysreset all bits to zero.
Coming back to C, let me explain the necessity of pointers through a simple program.
Consider swapping two numbers from their variables. This can be done easily within the
main() function. But suppose we need to do that to a lot of variables/multiple times in
our program. So we write a function where we pass the two variables as arguments. The
function performs the operation and program execution comes back to the main
function. So in the next line we print the variables and expect the values to be swapped
#include<stdio.h>
main()
{
int i = 3, *j, **k; j = &i; k = &j;
printf("\nAddress of i = %u", &i);
printf("\nAddress of i = %u", j);
printf("\nAddress of i = %u", *k);
printf("\nAddress of j = %u", &j);
printf("\nAddress of j = %u", k)
; printf("\nAddress of k = %u", &k);
printf("\nValue of j = %u", j);
printf("\nValue of k = %u", k);
printf("\nValue of i = %d", i);
printf("\nValue of i = %d", *(&i));
printf("\nValue of i = %d", *j);
printf("\nValue of i = %d", **k);
}
Output :
Address of i = 65524
Address of i = 65524
Address of i = 65524
Address of j = 65522
Address of j = 65522
Address of k = 65520
Value of j = 65524
Value of k = 65522
Value of i = 3
Value of i = 3
Value of i = 3
Value of i = 3
Variable
Actual Value
Value of i
Value of j
65524
Value of k
65522
Address of i
65524
Address of j
65522
Address of k
65520