C Programming language

Pointer in C :Definition and declaration
Previous Home Next

Pointer

Generally a pointer is a variable which keeps the address of another variable. pointer points to a memory location in which data is stored. Each memory cell in the computer has an address that can be used to access that location. through the pointer we can change the contents of memory locations.

Pointer declaration

A pointer is a variable that contains the memory location of another variable. The syntax is as shown below. You start by specifying the type of data stored in the location identified by the pointer. The asterisk tells the compiler that you are creating a pointer variable. Finally you give the name of the variable.

type * variable name 

Example

int *ptr; 
float *string;

 

Address operator

Once we declare a pointer variable we must point it to something we can do this by assigning to the pointer the address of the variable you want to point as in the following example:

ptr=# 

This places the address where num is stores into the variable ptr. If num is stored in memory 21260 address then the variable ptr has the value 21260.

Another declaration to the pointer is given below:

int*alpha;

char*ch;

float*s;

Here above alpha,ch and s are declared as the pointer variable and trually these three can hold the address of next variable according to above declaration. so we can say that pointers are variables that contain addresses, and since addresses are always whole numbers, pointers would always contain whole numbers

/* A program to illustrate pointer declaration*/ 

main() 
{ 
int *ptr; 
int multiplication; 
multiplication=20; 
ptr=*
printf (“\n Sum is %d\n”, sum); 
printf (“\n The sum pointer is %d”, ptr); 
}

we will get the same result by assigning the address of num to a regular(non pointer) variable. The benefit is that we can also refer to the pointer variable as *ptr the asterisk tells to the computer that we are not interested in the value 21260 but in the value stored in that memory location. While the value of pointer is 21260 the value of sum is 45 however we can assign a value to the pointer * ptr as in *ptr=45.

This means place the value 45 in the memory address pointer by the variable ptr. Since the pointer contains the address 21260 the value 45 is placed in that memory location. And since this is the location of the variable num the value also becomes 45. this shows how we can change the value of pointer directly using a pointer and the indirection pointer.

/* Program to display the contents of the variable their address 
using pointer variable*/
include< stdio.h > { int num, *intptr; float x, *floptr; char ch, *cptr; num=123; x=12.34; ch=’a’; intptr=&x; cptr=&ch; floptr=&x; printf(“Num %d stored at address %u\n”,*intptr,intptr); printf(“Value %f stored at address %u\n”,*floptr,floptr); printf(“Character %c stored at address %u\n”,*cptr,cptr); }
Previous Home Next