Pointers - Intermediate

Increment and Scale factor
As  mentioned in the previous tutorial on pointers, we can use increment and decrement operators with pointers.
int *ptr;
And say ptr has value 1012.
Then ptr++ sets  ptr to 1014 and not 1013.
The idea is that
ptr++ is equivalent to
 
ptr=ptr + (size_of datatype_pointed by ptr(int in this case))
 
Thus when we increment a pointer, its value is increased by the length of the data type that it points to. This length is called scale factor.
The same concept is also applicable to decrement operators as well as any addition / subtraction operation.
 
 
Pointers as arrays
 
In C there is a strong relationship between pointers and arrays, strong enough that pointers and arrays are often discussed simultaneously. Any operation that can be achieved by array subscripting can also be done with pointers.. The pointer version will  in general be faster but at least to the uninitiated, somewhat harder to understand.
 
Consider this array
 
int x[5]={1,2,3,4,5};
If we declare ptr as a integer pointer,then we can make pointer ptr to point to the array x by following sassignment
ptr=x;
This is equivalent to
ptr=&x[0];
 Now we can access every value of x using ptr++ to move from one element to another.
 
When handling arrays, instead of using array indexing , we can use pointers to access array elements. Note *(ptr+3) gives the value of x[3]. The pointer method is much faster than array indexing.
 
Example 1
 
#include<stdio.h>
int main()
{
int x[7]={1,4,3,8,5,8,7};
int *ptr, sum,i=0;  
ptr=x; printf("\tValue\t  Address");
while(i++<7)
{
printf(“  x[%d]   %d  %u  \n”,i,*ptr,ptr); //%u  addresses are
      unsigned integers sum+=*ptr;
ptr++;
}
printf(“\n Sum = %d”,sum);
}
 
Output
Output of Example 1
 
Pointer to Multi-dimensional arrays
 
In the previous section we described manipulation of single dimensional arrays using pointers. Now we extend this concept to multi-dimensional arrays.
In one dimensional arrays
                        *(x+i) or *(ptr+i)
represents the element x[i]. Similarly an element in a two dimensional array can be represented by the pointer expression
            *(*x+i)+j)        or       *(*ptr+i)+j)
 
Figure 1
 
Figure 1 illustrates how this expression represents the element a[i][j]. The base address of the array a is &a[0][0] and starting at this address, the compiler allocates contiguous space for all the elements, row-wise. That is, the first element of the second row is placed immediately after the last element of the first row, and so on. Suppose we declare an array a as follows:
 
int a[3][4]={{15,27,11,35},
{22,19,31,17},
{31,23,14,36}};
 
 
If we declare ptr as an int pointer with the initial address of &a[0][0],then
 a[i][|] is equivalent to "(ptr+4 x i + j)
 
You may notice that, if we increment i by 1, the ptr is incremented by 4, the size of each row, making ptr element a[2][3] is given by *(ptr+2 x 4 + 3) = *(ptr+11).
 
This is the reason why, when a two-dimensional array is declared, we must specify the size i each row so that the compiler can determine the correct storage mapping.
 
 
Pointers as character strings
 
A String  is basically an array of characters , terminated with a null character.
Thus the way we accessed integer arrays , similarly we can access character arrays.
 
This is illustrated by the following example
 
Example 2
#include<stdio.h>
int main()
{
char *name;
name=”DELHI”;
int len;
char *chptr=name;

while(*chptr!=0)        //check for NULL character
{
printf(“%c is stored at address %u\n”,*chptr,chptr);
chptr++;
}
len=chptr-name;         //chptr is at end of string
printf(“\n Length of string = %d \n”,len);
}
 
Output
Output of Exapmle 2
 
Array of pointers
 
we can declare an array of pointer as
int *ptr_arr[5];
it declares an array ptr_arr conatinig 5 integer pointers.
 
This approach is often used for creating an array of strings. The following eexample illustrates this concept
 
Example 3
#include<stdio.h>
int main()
{
int i;
char *names[]=
      {
      “nitesh”,
      “shubham”,
      “shashwat”,
      “botskool”,
      }
for(i=0;i<4;i++)
printf(“ \n %s ”,names[i] );
return 1;
}
Output
Output of Example 3
 
Pointers to derived data types
 
Till now we have been limiting our use of pointers to fundamental data types only. This was just for the sake of convenience.
We can also  uses pointer to derived data types (like structures ) also. The only differnce is the use of '->' operator instead of the '.'(dot)  operator for refering the data mambers of the object
 
Example 4
 
#include<stdio.h>
struct  student
{
int rollno;
char name[20],sex;
};

struct student *node,temp;    //declaring pointer to structure object

 

 
int main()

 

{

 

temp.rollno=1;
temp.sex='M';
strcpy(temp.name,”nitesh”);
node=&temp;
printf(“\nName : %s“,node->name);     // -> operator has been used
printf(“\nSex : %c“,node->sex);       // fo referencing members
printf(“\nRoll No : %d“,node->rollno);
return 1;
}
 
Output
Output of Example 4
 
NOTE:
The scale factor in this case will be the size of object(i.e 23 bytes for above structure)
 
Dynamic memory Allocation

The greatest advantage of pointers is their ability to implement dynamic memory allocation.
 
C provides three distinct ways to allocate memory for objects:
Static memory allocation:
space for the object is provided in the program at compile-time; these objects have an extent(or lifetime) as long as the program which contains them is loaded into memory
Automatic memory allocation:
temporary objects can be stored on the, and this stack is automatically freed and reusable after the block in which they are declared is exited
Dynamic memory allocation:
blocks of memory of arbitrary size can be requested at run-time using library functions such as malloc from a region of memory called the heap ; these blocks persist until subsequently freed for reuse by calling the library function free.
The advantage of dynamic memory allocation is that since the size of the data is usually known only at run-time , we  can allocate memory at run-time thus preventing  any wastage of memory(as in the case of arrays)
As mentioned dynamic memory allocation is implemented using the functions malloc() and free().
 
malloc()-allocates requested size of bytes and returns a pointer to the first byte of the allocated space
Syntax : pointer_variable=(cast-type*) malloc(element-size)
 
calloc()- allocates space for an array of elements, initializes them to zero and then returns a pointer to the memory
Syntax : pointer_variable=(cast-type*) malloc(no_of_elements,element-size)
 
realloc()-  modifies the size of previously allocated space
Syntax : pointer_variable=realloc(pointer_variable,new_element-size)
 
free() -frees memory allocated by alloc functions.
Syntax: alloc(pointer_to_memory to be freed)
 
 the application of alloc functions will be illustrated when we study linked list and other related topics.

 

Comments

Member since:
27 May 2009
Last activity:
8 years 29 weeks

Ya this content is very helpful to me an i am an engineering stident and lerning this language.

ROBOTS ARE MY HEART