C Language

What is a pointer in c

In C Language by Baqir AliLeave a Comment

A pointer provides a way of accessing a variable ( or a more complex kind of data, such as an array) without referring to the variable directly. The mechanism used for this is the address of the variable.

Why Pointer?

Pointers are used in situations when passing actual values is difficult or undesirable. Some reasons to use pointers are:

  • To return more than one value from a function.
  • To pass arrays and strings more conveniently from one function to another.
  • To manipulate arrays more easily by moving pointers to them (or to parts of them), instead of moving the arrays themselves.
  • To create complex data structures, such as linked lists and binary trees, where one data structure must contain references to other data structures.
  • To communicate information about memory, as in the function malloc(), which returns the location of free memory by using a pointer.

More about pointers

void main(void)
{
    int v=10;
	int *pv;
	pv=&v;
	printf(“\n  v  = %d”,v);
	*pv = *pv + 10;
	printf(“\n  v = %d”, *pv):
    getch();
} 

Suppose that v is a variable that represents some particular data item.

  • This variable is stored at a particular location in memory.
  • The variable can be accessed if its location, or address, in memory is known.

The address of v‘s memory location is determined by the expression &v.

Pointer Example
Pointer Example

Operation of the example program

Operations of Pointers
Operations of Pointers

The & Operator

& is an unary operator known as the address operator. A function call such as

scanf(“%d”, &v) 

It causes an appropriate value to be stored at a particular address in memory. The expression &v provides the address of the variable v, also called a reference to v.

The * Operator

* is a unary operator, called the dereference or indirection operator, which only operates on pointer variables. In simple terms, the * operator is the inverse of the address operator &.

More about pointers

Suppose that we assign the address of v to another variable pv. In other words,

pv = &v

This new variable is called a pointer to v, since it points to the location where v is stored in memory. Remember, however, that pv represents v ‘s address and not its value. The data item represented by v (i.e., the data item stored at v’s memory location) can be accessed via the expression *pv.

Thus, *pv and v both represent the same data item. Furthermore, if the statements

pv=&v and u=*pv 

then both u and v represent the same value.

Leave a Comment