Jan 19, 2017

Pointers in C


What is pointer?

 A pointer is a special kind of variable in C and C++ that holds the address of another variable.

Declaring pointer
A pointer is declared using indirection (*) operator. The typical direction of pointer is:

datatype  *pointer-name.

If a pointer “a” is pointing to an integer, it is declared as:

int *a

Pointer is useful due to following reasons/ Why do we need Pointer?

1. They enable us to access variable that is defined outside function
2. Pointers are efficient in handling data table sometimes even arrays.
3. Pointer tends to reduce length and complexity of algorithm
4. They increase the execution speed.
5. Uses of pointers allow easy access to character string.

Addressing concept


Computers store data in memory slots. Each slot has an unique address. Pointer stores the address of another entity. It refers to a memory location.

int i = 5;
int *ptr;                      /* declare a pointer variable */
ptr = &i;                      /* store address-of i to ptr */
printf(“*ptr = %d\n”, *ptr);   /* refer to referee of ptr */

What actually ptr is here?

ptr is a variable storing an address. ptr is NOT storing the actual value of i

int i = 5;
int *ptr;
ptr = &i;
printf(“i = %d\n”, i);
printf(“*ptr = %d\n”, *ptr);
printf(“ptr = %p\n”, ptr);


Example:Call by Value

void f(int j)
{
  j = 5;
}
void g()
{
  int i = 3;
  f(i);
}
After executing above coding output will be 3.


Example: Call by reference

void f(int *ptr)
{
  *ptr = 5;
}
void g()
{
  int i = 3;
  f(&i);
}
After executing above coding output will be 5


Pointer Arithmetic and Array

Y=*p1 * *p2;
Sum=sum + *p1;
z= 5* - *p2/*p1;
*p2=*p2 + 10;
=(*p1) * (*p2);

=(5 * (-(*p2)))/(*p1);

More Pointer Arithmetic
What if a is a double array?
A double may occupy more memory slots!
Given double *ptr = a;
What’s ptr + 1 then?
Addr Content Addr Content Addr Content Addr Content
1000 a[0]: 37.9 1001 1002 1003
1004 a[1]: 1.23 1005 1006 1007
1008 a[2]: 3.14 1009 1010 1011



Arithmetic operators + and – auto-adjust the address offset
According to the type of the pointer:
1000 + sizeof(double) = 1000 + 4 = 1004


No comments:

Post a Comment