Thursday, 3 August 2017

Pointers


In any programming language the variables are stored in some memory locations with some addresses.Some programming languages like c,provides a way for accessing these memory locations .This facility is provided with a well known concept called pointers.So,lets look at pointers

What is a pointer?

Most of the programmers feel pointers as difficult but its little bit tricky.Inshort,pointers are the variables that can store address of another variables. lets define a pointer

int *p;

The above declaration confirms that p is an integer pointer.* is used to indicate a variable as a pointer variable.

Example

int main()
{
 int *p,a=10;
 p=&a;
 printf("The address of a is %d\n",p);
 printf("The value of a is %d%",*p);
}

Output

The address of a is 339631052
The value of a is 10

From the above code,it is clear that the address of variable a is stored in p.address operator(&) is used to get the address of a variable.* is a dereferenceing operator used to retrieve the value stored in the address location.

Arithmetic operations on pointers:

The following are the invalid arithmetic operations on pointers.

  • Addition
  • Multiplication
  • Division
  • Modulo

The above operations are invalid because pointers contain addresses so performing the above operations on pointers results meaningless results. However,Subtraction is legal among pointers as it results to the offset between the addresses.

Interesting concepts of pointers


Pointer array vs array of pointers


pointer array


Pointer array is a pointer pointing to an array.
int main() 
{
 int *p,arr[5],i;
 p=&arr; // p is pointing to array arr
 for(i=0;i<5;i++)
 {
     scanf("%d",&arr[i]);
 }
 for(i=0;i<5;i++)
 {
     printf("%d",*(p+i));
 }
    return 0;
}

Output

12345

Array of pointers

Array of pointers is an array containing addresses as array elements.

   
int main()
{
 int *arr[5],i;
 for(i=0;i<5;i++)
 {
  arr[i]=&i;
 }
 for(i=0;i<5;i++)
 {
  printf("%d\n",*arr[i]);
 }
}

Output

0
1
2
3
4

function pointer vs pointer to function


pointer to function


Function pointer is a pointer typically points to the block of executable code.

Example

void code(int i)
{
 printf("value of i is %d",i);
}
int main()
{
 void (*fun_ptr)(int)=&code;
 (*fun_ptr)(5);
 return 0;
}

Output

value of i is 5

Here we need an extra bracket around function pointer like fun_ptr,otherwise it becomes void *fun_ptr*(int) which is a function returning pointer.

function pointer

function pointer is function that returns pointer.

int *fun();
int main()
{
    int *ptr;
    ptr=fun();
    printf("%d",*ptr);
}
int *fun()
{
    int *pointer=malloc(sizeof(*pointer));
    *pointer=10;
    return pointer;
}

Output

10

No comments:

Post a Comment