Pointers

 

introduction to pointers

Pointer is a variable that holds a memory address, usually the location of another variable in memory. The pointers are one of C’s most useful and strongest features. Let i be an ordinary variable that stores the value of an integer. If p is another variable used to store the address of variable i, then p is called a pointer variable, pointing to i. A pointer must be preceded by an asterisk (*), while defining it, so that it is distinct from other variables. The definition of a pointer variable must also specify the type of data stored in the target variable pointed to it. In our example, the target variable is i, is holding integer type data, and hence, the pointer variable p must be defined as of the type int.

Here, i is the name of a variable that stores the value 10 and is stored in memory in the address, say 1234. This could be represented as follows :

1234

<— Address of the variable i  

10

<— Value of the variable i  

Now consider another variable, p, which holds the address of the variable i. Then p is said to be a pointer pointing to i. This again, could be graphically represented as :

 

1234

———–>

10

p

I

 

ADVANTAGES OF USING POINTERS

There are number of advantages of using pointers. They are :

  1. Pointers increase the speed of execution of a program.
  2. Pointers reduce the length and complexity of a program.
  3. Pointers are more efficient in handling the data tables.
  4. A pointer enables us to access a variable that is defined outside the function.
  5. The use of a pointer array to character strings results in saving of data storage space in memory.

 

 

DECLARING POINTERS

 

Like all variables, a pointer variable should also be declared. The syntax is :

                                    data_type *ptr_variable ;

Where data_type is the type of the pointer variable (ptr_variable) which may of any valid type. * is called as the indirection operator also referred to as the  de-referencing operator, which states that the variable is not an ordinary variable but a pointer variable. The ptr_variable is the name of the pointer variable. The rules for naming pointer variables are same as ordinary variables.

For example :

int *ptr ;

Will declare the variable ptr as a pointer variable that points to an integer data type.

INITIALIZING POINTERS

It is always good practice to initialize pointers as soon as it is declared. Since a pointer is just an address, if it is not initialized, it may randomly point to some location in memory. The ampersand (&) symbol, also called address operator, is applied to a variable to refer the address of that variable. Initializing pointers can be made to point to a variable using an assignment statement. The syntax is :

                        ptr_variable = &variable ;

Here, the address of the variable is assigned to ptr_variable as its value. For example :

ptr = &price ;

Will cause ptr to point to price i.e., ptr now contain the address of price. A pointer variable can be initialized in its declaration itself. For example :

int price, *ptr = &price ;

Is also valid.

 

Arithmetic operations on pointer variables

C pointer is an address which is a numeric value. Therefore, you can perform arithmetic operations on a pointer just as you can a numeric value. There are four arithmetic operators that can be used on pointers: ++, –, +, and –

 

To understand pointer arithmetic, let us consider that ptr is an integer pointer which points to the address 1000. Assuming 32-bit integers, let us perform the following arithmetic operation on the pointer:

ptr++

Now after the above operation, the ptr will point to the location 1004 because each time ptr is incremented, it will point to the next integer location which is 4 bytes next to the current location. This operation will move the pointer to next memory location without impacting actual value at the memory location. If ptr points to a character whose address is 1000, then above operation will point to the location 1001 because next character will be available at 1001.

 

Incrementing a Pointer

We prefer using a pointer in our program instead of an array because the variable pointer can be incremented, unlike the array name which cannot be incremented because it is a constant pointer. The following program increments the variable pointer to access each succeeding element of the array:

 

#include <stdio.h>

const int MAX = 3;

int main ()

{

   int  var[] = {10, 100, 200};

   int  i, *ptr;

   /* let us have array address in pointer */

   ptr = var;

   for ( i = 0; i < MAX; i++)

   {

      printf(“Address of var[%d] = %x\n”, i, ptr );

      printf(“Value of var[%d] = %d\n”, i, *ptr );

 

      /* move to the next location */

      ptr++;

   }

   return 0;

}

When the above code is compiled and executed, it produces result something as follows:

Address of var[0] = bf882b30

Value of var[0] = 10

Address of var[1] = bf882b34

Value of var[1] = 100

Address of var[2] = bf882b38

Value of var[2] = 200

 

 

Decrementing a Pointer

The same considerations apply to decrementing a pointer, which decreases its value by the number of bytes of its data type as shown below:

#include <stdio.h>

const int MAX = 3;

int main ()

{

int  var[] = {10, 100, 200};

int  i, *ptr;

/* let us have array address in pointer */

ptr = &var[MAX-1];

for ( i = MAX; i > 0; i–)

{

printf(“Address of var[%d] = %x\n”, i, ptr );

printf(“Value of var[%d] = %d\n”, i, *ptr );

/* move to the previous location */

ptr–;

}

return 0;

}

When the above code is compiled and executed, it produces result something as follows:

Address of var[3] = bfedbcd8

Value of var[3] = 200

Address of var[2] = bfedbcd4

Value of var[2] = 100

Address of var[1] = bfedbcd0

Value of var[1] = 10

 

 

Pointer Comparisons

Pointers may be compared by using relational operators, such as ==, <, and >. If p1 and p2 point to variables that are related to each other, such as elements of the same array, then p1 and p2 can be meaningfully compared.

The following program modifies the previous example one by incrementing the variable pointer so long as the address to which it points is either less than or equal to the address of the last element of the array, which is &var[MAX - 1]:

#include <stdio.h>

const int MAX = 3;

int main ()

{

int  var[] = {10, 100, 200};

int  i, *ptr;

/* let us have address of the first element in pointer */

ptr = var;

i = 0;

while ( ptr <= &var[MAX - 1] )

{

printf(“Address of var[%d] = %x\n”, i, ptr );

printf(“Value of var[%d] = %d\n”, i, *ptr );

/* point to the previous location */

ptr++;

i++;

}

return 0;

}

When the above code is compiled and executed, it produces result something as follows:

Address of var[0] = bfdbcb20

Value of var[0] = 10

Address of var[1] = bfdbcb24

Value of var[1] = 100

Address of var[2] = bfdbcb28

Value of var[2] = 200

 

 

Pointer with array

 

let us start: An array name is a constant pointer to the first element of the array. Therefore, in the declaration:

double balance[50];

 

balance is a pointer to &balance[0], which is the address of the first element of the array balance. Thus, the following program fragment assigns p the address of the first element of balance:

 

double *p;

double balance[10];

p = balance;

 

It is legal to use array names as constant pointers, and vice versa. Therefore, *(balance + 4) is a legitimate way of accessing the data at balance[4].

Once you store the address of first element in p, you can access array elements using *p, *(p+1), *(p+2) and so on. Below is the example to show all the concepts discussed above:

 

#include <stdio.h>

int main ()

{

   /* an array with 5 elements */

   double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};

   double *p;

   int i;

   p = balance;

   /* output each array element’s value */

   printf( “Array values using pointer\n”);

   for ( i = 0; i < 5; i++ )

   {

       printf(“*(p + %d) : %f\n”,  i, *(p + i) );

   }

   printf( “Array values using balance as address\n”);

   for ( i = 0; i < 5; i++ )

   {

       printf(“*(balance + %d) : %f\n”,  i, *(balance + i) );

   }

 

   return 0;

}

 

When the above code is compiled and executed, it produces following result:

Array values using pointer

*(p + 0) : 1000.000000

*(p + 1) : 2.000000

*(p + 2) : 3.400000

*(p + 3) : 17.000000

*(p + 4) : 50.000000

 

Array values using balance as address

 

*(balance + 0) : 1000.000000

*(balance + 1) : 2.000000

*(balance + 2) : 3.400000

*(balance + 3) : 17.000000

*(balance + 4) : 50.000000

In the above example p is a pointer to double which means it can store address of a variable of double type. Once we have address in p, then *p will give us value available at the address stored in p, as we have shown in the above example.

 

 

Pointer with structure

Pointer to structure: A pointer which is pointing to a structure is know as pointer to structure.

Examples of pointers to structure:

What will be output if you will execute following code?


#include<stdio.h>

struct address{

char *name;

char street[10];

int pin;
}cus={“A.Kumar”,”H-2″,456003},*p=&cus;

 

int main(){

printf(“%s %s”,p->name,(*p).street);

return 0;

}

Output: A.Kumar H-2

 

Explanation:

p is pointer to structure address.

-> and (*). Both are same thing. These operators are used to access data member of structure by using structure’s pointer.

 

 

 

 

 

 

 

 

Registration


A password will be e-mailed to you.

Feedback Form

Name (required)

Email (required)

Feedback