Pointer basic example

We has been discuss about what is pointer and concept of pointer. Now the following program demonstrates the relationship of our pointer discussion.

#include<stdio.h>
int main()
{
   int x = 5;
   int *y;

   y = &x;
   printf("\nAddress of x = %u", &x);
   printf("\nAddress of x = %u", x);
   printf("\nAddress of y = %u", &y);
   printf("\nValue of y = %d", y);
   printf("\nValue of x = %d", x);
   printf("\nValue of x = %d", *(&x));
   printf("\nValue of y = %d", *y);

  getch();
  return 0;
}

The output of above program would be:

Address of x = 2293620
Address of x = 5
Address of y = 2293616
Value of y = 2293620
Value of x = 5
Value of x = 5
Value of y = 5

/* Screen shot for above program */

Output of pointer basic example C program
Screen-shot for pointer basic example C program


note: the address of variable may be differ because its depend on compiler. I use Bloodshed software "Dev-C++" so you can see that here integer occupy 4 bytes.

The above program summarizes everything that we discussed in what is pointer and concept of pointer chapters. If you don't understand the program output, or the meaning of &x, &y, *y and *(&x), re-read the last 2 chapter of pointer:
What is pointer
Concept of pointer

Now look at the following declaration:

int *n;
char *ch;
float *area;

Here, n, ch and area are declared as pointer variable, i.e. these variable capable of holding addresses.
Keep in mind: Address ( location numbers ) are always whole numbers.
In summarize "we can say pointers are variable that contain addresses and addresses are always whole numbers."

The declaration float *area does not mean that area is going to contain a floating-point value. The meaning is, *area is going to contain the address of a floating-point value.
Similarly, char *ch means that ch is going to contain the address of a char value or in other words, the value at address stored in ch is going to be a char.

Now we know that "Pointer is a variable that contains address of another variable."
Can we further extended it? The answer is Yes, we can. Read in next chapter "Pointer Extended Example".


Related programs:


  1. What is pointer ?
  2. Concept of Pointer
  3. Pointer extend example

Comments