Pointers

C Tutorials

Introduction

One of those things beginners in C find difficult is the concept of pointers. The purpose of this tutorial is to provide an introduction to pointers and their use to these beginners.

 
A pointer is a variable that contains the memory location of another variable. The values you assign to the pointers are memory addresses of other variables.
 
The idea is that every variable that is used in a program is first assigned a memory location . In case of normal variables (i.e which are not pointers) the variable name refers to the value stored in that location. However when we come to pointers, the variable name refers to the address of that memory location.
 
Declaration
        <data-type> * <variable name>

First of all, specify the data type of data stored in the location, which is to be identified by the pointer. The asterisk tells the compiler that you are creating a pointer variable. Then specify the name of variable.
 
Data type can be any valid data type used in C – int, float, char, struct etc. For simplicity we will now stick to the fundamental data types only.
Variable name can be any valid identifier.
 
Example:
These are some valid pointer declarations
    int *ptr;                   //declares ptr as pointer to integer value
    char *name;             //declares name as pointer to a single character
    int *ptr1, i;              //ptr1 is a pointer and i is an integer
 
Note:
Any pointer needs to be initialized before it can be used (you can always try and use an uninitialized pointer to see some weird results!). This prevents the program from referencing any arbitrary position in memory, thus preventing access violations.
Initialising is discussed later in this tutorial.

 

 

  
 
 

A word about memory organisation

 

 
Let us begin with a simplified picture of how memory is organised. A typical machine has an array of consecutively numbered or addressed memory cells that may be manipulated individually or in contiguous groups. One common situation is that any byte can be a char, a pair of one-byte cells can be treated as a short integer, and four adjacent bytes form a long. A pointer is a group of cells(often two or four) that can hold an address.
 
Pointers - Figure 1


Figure 1 shows a typical memory arrangement for any system. Each block corresponds to 1 byte.

 
Consider the statement -
 
int a=56;
 
The system allocates memory for a integer variable and stores the value 56 in it. The graphical depiction is shown in figure 2.
Figure 2
Now, consider this pointer declaration -
 
int *ptr;
 
Now another variable named ptr is created, say it is assigned memory location 1012. Now at this memory location the address of another variable will be stored (say location of a i.e 988 is stored)
 
Since the value of the variable ptr is the address of the variable a, we may access the value of a by using the value of ptr and therefore, we can say that the variable ptr points to the variable a. Thus ptr gets the name pointer.
 
 
 

Working with pointers

 

 

 

 

 

Initialisation

 

 
Before we move further, an operator needs to mentioned. It is the '&' or referencing operator. This is a unary operator which returns the memory location of its operand (usually a variable). For example in the figure 2 above &a gives 988. The use of this operator facilitates the initialization of pointers.
 
As already pointed out the pointer name refers to the address of some memory location, i.e. if ptr points to location 1012 in memory and value stored at that location is 56, then p will be 1012 and *p (explained later )will be 56
 
For initializating a pointer we need to supply it with an address. One common way is to assign the address of another variable to it.
 
int *ptr,a=56;                 //note the use of & operator
ptr=&a;                          //ptr now points to a
 
where -&a is an address and p also stores an address, hence the assignment p=&a is legal.
 
Pointers can also be initialised with the help of malloc() function which will be discussed later on.
 
 

Reading and Storing values

 

To access (read or change) the value stored (actually pointed to) by the pointer variable we make use of the '*' or the indirection (or deferencing) operator.
 
 
 

Example 1:

 

 
 

 

/*******************************

                www.botskool.com

********************************/

#include<conio.h>

void main()

{

 

int *ptr,a=5;             //initialisation

clrscr();

ptr=&a ;

printf("Value of a is %d",*ptr);       //note the use of * operator

getch();

 

}                        //the output will be 5

 

/*******************************

                www.botskool.com

********************************/

 

 
 
Output will be like this:
 
Output of example 1 (Pointers)
 
Download source code.
 
 
 

Example 2:

 

 
  

/*******************************

    www.botskool.com

*******************************/

#include<conio.h>

void main()

{

 

int *ptr,a,b;

clrscr();

a=5;b=6;

ptr=&a;

printf("*ptr = %d and a = %d",*ptr,a);

*ptr=b;           //this will also change the value of a .Think why?

printf("\n*ptr = %d and a = %d",*ptr,a);

getch();

 

}

/*******************************

    www.botskool.com

*******************************/

 
 
Output will be:-
 
Output of example 2 (Pointers)
 
Download source code.
 
 
Note that the value of a has been changed.
 
Pointer arithmetic
 
The pointer variable stores memory addresses which are nothing but integers. Can we apply usual arithmetic operations on pointers? Well not all but some operations are valid on pointers also.
We can basically add and subtract pointer variables.
If p1 and p2 are pointers to same data type then
p1- p2, p1+p2 , p1++ , p2-- , --p1 , p1+3 (multiplication, division not allowed)
p1<=p2, p1==p2 etc               (and other relational operations)
 
 
Important
 
  • Though subtraction and addition of two pointers is allowed it must be used with great caution because the result of such operation may seem to be correct but it may not be a valid memory address. For example negative addresses do not exist. Thus the use of pointer arithmetic is usually limited to increment (++) and decrement (--) operators. This will be illustrated when we work with arrays and pointers.
  • *ptr ==>> this expression acts like any other non-pointer variable in a expression
For example the expression
y=*p1**p2;
may seem complicated but it is a perfectly valid expression which multiplies the values pointed by p1 and p2.
i.e. y=(*p1)*(*p2);

 

Comments

Member since:
28 April 2009
Last activity:
6 years 51 weeks

I guess that is true, it all depends on the system. I was working too much with 8 bit Microcontroller compilers with int designated as 2 bytes so it skipped my mind. My apologies

Member since:
8 April 2009
Last activity:
7 years 43 weeks

integers are not always 2 bytes. It depends upon the system you are working with

and the compiler you are using.

for most 32 -bit systems its 4 bytes and not 2

on DOS and other 16-bit systems its  2 bytes

 

run this code to see the result

 

#include<iostream.h>

using namespace std;

int main()

{

cout<<"int size"<<sizeof(int)<<endl<<" ptr "<<sizeof(int*);

return 1;

}

 

 

Member since:
28 April 2009
Last activity:
6 years 51 weeks

You can only pass an address to a pointer. So even with integers you need to pass the address as &x and not x alone when calling a function as stated in the example as well.

A pointer is incremented or decremented depending on the data type. For example, in case of  integers 2 bytes are incremented

Member since:
21 February 2009
Last activity:
7 years 1 week

No you cannot use *ptr as argument in square() function since this (*ptr) represents an integer value to which pointer ptr is pointing while argument should be of integer pointer type .

 

square (*ptr); //This statement is illegal

 

The prototype of the function is as follows-

void square(int *pointer); /* prototype */

The argument passed in this function must be integer pointer type.

Member since:
30 March 2009
Last activity:
7 years 36 weeks

thanx a lot.......

Bt i have doubt !!

Is following function call wrong??

square(*ptr);

Member since:
21 February 2009
Last activity:
7 years 1 week

 

#include <conio.h>
#include <stdio.h>
 
void square(int *pointer); /* prototype */
 
void main()
{
  
   int *ptr;
   int x=10;
   clrscr();
   ptr=&x;
   square(ptr);
   square(&x); /*You can also pass values like this*/
   getch();
 
}
 
void square(int *pointer)
{
    *pointer = (*pointer)*(*pointer);
    printf("The value is %d\n", *pointer); /*Prints square of the number*/
 
 
}

Output will be like this:-

Passing pointer in a function

 

Note: The same query has been copied and posted in forum also.

Member since:
30 March 2009
Last activity:
7 years 36 weeks

can u plz tell me that how a pointer is passed in a function....

give a brief intro to the example...what are u goin to do?