Introduction to Pointer
A pointer is special type of a variable. It is special because it contains a memory address instead of values. A pointer variable is declared with specific data type, like any other normal variable so that it will work only with memory address of a given type.
data-type * variable_ name;
Example
Write a program to read marks of 10 students secured in a subject and store them in an array using pointer notation. Calculate average marks of them and display on screen.
int main() { int marks [10] , i, sum=0; float avg; print f("Enter marks of each student"); for(i=0; i<10; i++) { scan f("%d", marks+i); sum+=*(marks+i); } avg=sum/10; print f("The average is %f", avg); getch (); return 0; Output Enter marks of each student: 56 90 65 45 34 23 89 67 56 78 The average is =60.00000
Dynamic Memory Allocation(DMA)
The process of allocating and freeing memory in a program at run time is known as Dynamic Memory Allocation (DMA).
i. malloc () function
It allocates requested size of bytes and returns a pointer to the first byte of the allocated space to the program.
ptr = (data_ type*) malloc (size_ of_ block);
Example
x=(int*) malloc (100* sizeof (int));
ii. calloc() function
ptr = (data_ type*) calloc(no_ of_ blocks, size_ of_ each_ block);
Example
x= (int*) calloc (5, 10*sizeof (int));
x= (int*) calloc( 5, 20);
iii. free() function
free (ptr)
iv. realloc();
ptr= realloc (ptr, newsize)
Example
write a program to define two matrices of order m×n using pointer notation. Read elements of the matrices from user and add them using pointer.
#define m 2 #define n 3 int main() { int (*a) [n], (*b) [n], *(sum) [n], i, j; print f ("Enter first matrix"); for(i=0; i<m; i++) for(j=0; j<n; j++) scan f("%d", *(a+i)+j); print f ("Enter second matrix"); for(i=0; i<m; i++) for(j=0; j<n; j++) scan f("%d", *(b+i)+j); print f("The sum matrix is"); for(i=0; i<m; i++) { for(j=0; j<n; j++) { *(*(sum+i)+j)= *(*(a+i)+j)+ *(*(b+i)+j); print f("%d"), *(*(sum+i)+j)); } print f("\n"); } getch (); return 0; } Output Enter first matrix: 1 2 3 3 4 6 Enter second matrix: 4 6 7 7 4 2 The sum matrix is: 5 8 10 10 8 8