0
1.1kviews
What is Pointers?
1 Answer
0
10views

Pointers are another important feature of C language. Although they may appear a little confusing for a beginner, they are powerful tool and handy to use once they are mastered.

There are a number of reasons for using pointers.

  1. A pointer enables us to access a variable that is defined outside the function.

  2. Pointers are more efficient in handling the data tables.

  3. Pointers reduce the length and complexity of a program.

  4. They increase the execution speed.

  5. The use of a pointer array to character strings result in saving of data storage space in memory.

Accessing The Address Of A Variable

The actual location of a variable in the memory is system dependent and therefore, the address of a variable is not known to us immediately. However we determine the address of a variable by using the operand & available in C. The operator immediately preceding the variable returns the address of the variable associated with it. For example, the statement

p = &quantity;

would assign the address 5000(the location of quantity) to the variable p. The &operator can be remembered as ‘address of’.

Understanding Pointers

Whenever we declare a variable, the system allocates, somewhere in the memory, an appropriate location to hold the value of the variable. Since, every byte has a unique address number, this location will have its own address number. Consider the following statement:

int quantity = 179;

This statement instructs the system to find a location for the integer variable quantity and puts the value 179 in that location. Assume that the system has chosen the address location 5000 for quantity. We may represent this as shown below.

quantity Variable

Value

5000 Address

179

Representation of a variable

During execution of the program, the system always associates the name quantity with the address 5000. To access the value 179 we use either the name quantity or the address 5000. Since memory addresses are simply numbers, they can be assigned to some variables which can be stored in memory, like any other variable. Such variables that hold memory addresses are called pointers. A pointer is, therefore, nothing but a variable that contains an address which is a location of another variable in memory.

Declaring and Initializing Pointers

Pointer variables contain addresses that belong to a separate data type, which must be declared as pointers before we use them. The declaration of the pointer variable takes the following form:

data type *pt _name;

Accessing a Variable through Its Pointer

To access the value of the variable using the pointer, another unary operator *(asterisk), usually known as the indirection operator is used. Consider the following statements:

int quantity, *p, n;

quantity = 179;

p= &quantity;

n= *p;

Please log in to add an answer.