Introduction
Pointers are a part of the C language and make the C language more powerful. The following arre some features ot them:
- A pointer mainly represents a data structure.
- It changes values of an actual argument passed to the function (“call by reference”).
- It is also for working with memory allocation dynamically.
- It is efficiently used with integer arrays and character arrays.
- A pointer always stores a memory address, not data values.
- A pointer holds the value aa an address.
Declaration
A pointer variable must be declared before use. The syntax for a pointer declaration is as follows.
Now a is a “pointer to an integer”and b is a “pointer to a double”.
The prefix * defines the variable as a pointer.
Example
Here a contains the memory address of the variable b.
Arithmetic operation are limited to the following for pointers:
- Integers and pointers can be added and subtracted.
- Incremented and decremented
- In addition, pointers can be assigned to each other
Example
Call by Reference
Using call by reference means that a parameter is sent to the function in the form of an address location.
- #include<stdio.h>
- Void swap(int *p , int *q);
- main()
- {
- Int i=3,j=5;
- swap( &I , &j );
- printf("After swap, i=%d j=%d\n" ,I ,j );
- getch();
- return 0;
- }
- Void swap(int *p, int *q)
- {
- Int temp;
- temp=*p;
- *p=*q;
- *q=temp;
- }
Output
Pointers and arrays
A pointer always contains the base address of the memory location that makes up an entire array.
Declaration
Example
- Int a[5];
- a[5]=10;
- *(a+5)=56;
All of those are the same thing.
Examples
-
- Int a[100] , I , *p , sum=0;
- for (i=0 ; i<100 ;++I )
- Sum += a[i];
-
- int a[100] , I , *p , sum=0;
- for (i=0 ; i<100 ; ++I )
- Sum += *( a + I );
-
- int a[100] , I , *p , sum=0;
- for ( p=a ; p<&a[100] ; ++p )
- sum += *p;
The following shows an array as function arguments:
- double sum(double *dp , int n )
- {
- Int I ;
- Double res=0.0 ;
- for ( i=0 ; i<n ; ++I )
- res += *( dp + I ) ;
- return res;
- }
That function needs a starting address in the array and the number of elements to be summed together.
Pointers and Character Strings
- #include<stdio.h>
- main()
- {
- Char *cp ;
- cp = "Neeraj Kumar";
- printf("%c\n" , *cp );
- printf("%c\n" , *( cp + 7 ));
- return 0;
- }
Output
We can use pointers to work with character strings. The value of the string constant address is the base address of the character array.
Thank you.