Monday, 16 January 2012

Pointers

One of the hard concepts that I encountered in C is pointers. However, pointers are very important and widely used in C (particularly for my case since I am using arrays) so I must understand how pointers work. According to Kernighan and Ritchie in their book “Programming Language in C”, a pointer is a variable that contains the address of a variable.

Here is an example how pointers work.

  1.  int * a; // define integer type pointer(int *) a
  2.  int b = 5;
  3.  a = &b; // & is get the address of the variable
  4. int d = *a; // * is same as int d = b


  1. Define the integer type pointer named a (In C, a is an int pointer which is stored in address 201)
  2. Define integer b and assign the value 5 to b (In C, b is 5 which is stored in address 301)
  3. a is pointing at the address of b (Now, a has the value of b’s address)
  4. * means getting the value of what a is pointing at. That is, a is pointing at b and the value of b is 5. Therefore, *a is 5. 5 is then assigned to d.

Here is the diagram of the example:





I will explain why pointers are important and useful later.

No comments:

Post a Comment