Pointers in c

A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to store any variable address. The general form of a pointer variable declaration is:-

type *var-name;

Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the pointer variable. The asterisk * used to declare a pointer is the same asterisk used for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Some of the valid pointer declarations are as follow:-

int    *ip;    /* pointer to an integer */

double *dp;    /* pointer to a double */

float  *fp;    /* pointer to a float */

char   *ch     /* pointer to a character */

The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to.




what is pointer ?

 Pointers are the variables that contain the address of another variable within the   memory.Like any variable or constant, you must declare a pointer before using it to store   any variable address.

Basics of pointers 

  • Every data item in the computer is stored in the memory in one or more adjacent  locations depending upon it’s type. 
  • Computers memory is sequential collection of storage cells. 

  • Example : int x=5;
              X      =      Variable
               5      =      Value
            1002   =      Address

          Representation of x=5 In memory 

  • Pointer is a variable that contain the address which is a location of another variable in the memory.

  • Suppose we assign address of x to variable p, then p is called the pointer, as it points variable x. the link between x and p is shown below:
          Address of  X  =  5
       
                P  X

          Link between variables x and p


Advantages of Pointers 
  •  Pointers are more efficient in handling arrays and data tables.
  •  Pointers return more than one value from a function.
  •  Pointers can pass arrays and string from one function to another.
  •  Pointers can create complex data structures, such as linked lists, stacks, queues.
  •  Pointers allow C to support dynamic memory management.
  •  Pointers reduce length and complexity of programs.
  •  Pointers increase the execution speed and thus reduce the program execution
  •   time.

How to Use Pointers?

Some important operations, which we will do with the help of pointers.

(a) : We define a pointer variable, 
(b) : Assign the address of a variable to a pointer and 
(c) : Finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand. 

Example:-

#include <stdio.h>

int main () {

   int  var = 20;   /* actual variable declaration */
   int  *ip;        /* pointer variable declaration */

   ip = &var;  /* store address of var in pointer variable*/

   printf("Address of var variable: %x\n", &var  );

   /* address stored in pointer variable */
   printf("Address stored in ip variable: %x\n", ip );

   /* access the value using the pointer */
   printf("Value of *ip variable: %d\n", *ip );

   return 0;
}


Output:-

Address of var variable: bffd8b3c
Address stored in ip variable: bffd8b3c
Value of *ip variable: 20

Address(&) and Dereferencing(*) operators:

  •  To access the address variable x, the operator & is used.
  •  ‘&’ is called ‘address of operator’ and it is unary operator.
  •  We can assign the address of x to another variable p as:
  •  p=&x; //Assigns 1002(address of x) to p .thus p is a pointer variable.
  •  Accessing the value of variable through pointer(using * 
  •  operator)
  •  The value represented by x, can be accessed by the expression *P, 
  •  where * is called ‘value at the address’ operator and it is a unary 
  •  operator.
  •  *p and x represent same value
  •  x and *p represent 5.
  •  * is called ‘dereferencing or indirection operator’.

Pointer declaration

  •  Syntax:
                data_type *ptvar;
  •  Examples:
                int *p; 
                float *abc;
                char * status;

Pointer Initialization

  • Syntax:
             datatype *ptr_var=&addr_var;
  •  Example:
             int a=5,x,*aptr;
             aptr=&a; //assign addr of a to pointer aptr
             x=*aptr; //asssign value at address pointed by ‘aptr’ to x i.e x=5
             *aptr=0; // assign value 0 to a

 Pointer Arithmetic


1.Operation: 
        Increment

   Expression :
        Ptr++; 

   Meaning:

   Increment ptr to point to next location of same type. If ptr is a pointer to                                 integer(int occupie 2 byte), if ptr=2003 then ptr++ gives ptr=2005.If ptr is a pointer to           character(char occupies 1 byte), if ptr=2003 then ptr++ gives ptr=2004.

2.Operation: 
        Decrement

   Expression :
        Ptr--;

   Meaning:
       
   Decrement ptr to point to previous location of same type. If ptr is a pointer to integer(int       occupie 2 byte), if ptr=2003 then ptr-- gives ptr=2001. If ptr is a pointer to character(char     occupies 1 byte), if ptr=2003 then ptr-- gives ptr=2002.

3.Operator:
         Adding a number to pointer

   Expression:
         ptr=ptr+8 

   Meaning:

   Ptr points to 8 integer locations after current location.
   If ptr=2003 then ptr+8 gives ptr=2011.

4.Operators:

           Subtracting a number from a pointer

    Expression:
            Ptr=ptr-6 
   
    Meaning:

    Ptr points to 6 integer locations before current locations.
    If ptr=2003 then ptr-6 gives ptr=1997.

5.Operators:

            Subtracting of one pointer from another pointer
 
    Expression:
            Ptr=ptr1-ptr2; 
  
    Meaning:

    We can subtract one pointer from another if and only if both are pointing to one array.

 Array with pointer variable

  •  When an array is declared, the compiler allocates a base address and storage 
  • to contain all the elements of the array in memory locations.
  •  The base address is the location of the first element (index 0) of the array.
  •  The compiler defines the array name as a constant pointer which contains the 
  • address of the first element of the array.
  •  Example :

               int x[5] = {1,2,3,4,5};
  •  Suppose, the base address of x is 1000, then the five elements will be stored as follows :
                  Elements   ----->
                  Value         ----->            1 2 3 4 5
                  Address     ----->

  • Here the array name x is a constant pointer that contains the address of first element, x[0].
  • Therefore x = &x[0] = 1000;
  • If we declare p as an integer pointer, then we can write 

                p = x; therefore p = &x[0];
  •  Now we can access every value of array x using p++ as follows :
                p = &x[0] ( = 1000) 
                p+1 = &x[1] ( = 1002) 
                p+2 = &x[2] ( = 1004) 
                p+3 = &x[3] ( = 1006) 
                p+4 = &x[4] ( = 1008)
  •  Now we can access array elements using pointer instead of array.

 Pointer as function arguments 


  • When the function change( ) is called, the address of variable x is passed into the function change( ).
  • Inside the change( ), the variable p is declared as pointer therefore p is the address of variable x.
  • The statement *p = *p + 10;
  • Add 10 to the value stored at the address p, so the value of x is changed from 20 to 30. Therefore the output of the program will be 30.


Example :

main( )
{
int x;
x = 20;
change(&x); 
printf(“%d\n”,x);
}
change(int *p)
{
*p = *p + 10;
}


NULL Pointers


A pointer that is assigned NULL is called a null pointer.

The NULL pointer is a constant with a value of zero defined in several standard libraries. Consider the following program :-


#include <stdio.h>

int main () {

   int  *ptr = NULL;

   printf("The value of ptr is : %x\n", ptr  );
 
   return 0;
}


Output:

The value of ptr is 0

In most of the operating systems, programs are not permitted to access memory at address 0 because that memory is reserved by the operating system. However, the memory address 0 has special significance; it signals that the pointer is not intended to point to an accessible memory location. But by convention, if a pointer contains the null (zero) value, it is assumed to point to nothing.

To check for a null pointer, you can use an 'if' statement as follows :-

if(ptr)     /* succeeds if p is not null */
if(!ptr)    /* succeeds if p is null */

Pointers in Detail

Pointers have many but easy concepts and they are very important to C programming. The following important pointer concepts should be clear to any C programmer −


Sr.No. Concept & Description

1               Pointer arithmetic
                      There are four arithmetic operators that can be used in pointers: ++, --, +, -

2               Array of pointers
                      You can define arrays to hold a number of pointers.

3               Pointer to pointer
                      C allows you to have pointer on a pointer and so on.

4               Passing pointers to functions in C
                      Passing an argument by reference or by address enable the passed argument                            to be changed in the calling function by the called function.

5               Return pointer from functions in C
                      C allows a function to return a pointer to the local variable, static variable,                              and dynamically allocated memory as well.

 (IMP)Swapping two number using pointer

#include<stdio.h>
void swap(int *num1, int *num2)
{
        int temp;
        temp = *num1;
        *num1 = *num2;
        *num2 = temp;
}
int main()
{
        int num1, num2;
        printf("\nEnter the first number : "); 
        scanf("%d", &num1);
        printf("\nEnter the Second number : "); 
        scanf("%d", &num2);
        swap(&num1, &num2); 
        printf("\nFirst number : %d", num1);
        printf("\nSecond number : %d", num2); 
        return (0);
}

OUTPUT:

Enter the first number: 12 
Enter the Second number : 22 
First number: 22
Second number : 12

C Program to Read integers into an array and Reversing them using Pointers

#include<stdio.h>
#include<conio.h>
#define MAX 30
void main() {
int size, i, arr[MAX];
int *ptr;
clrscr();
ptr = &arr[0];
printf("\nEnter the size of array : "); 
scanf("%d", &size);
printf("\nEnter %d integers into array: ", size); 
for (i = 0; i < size; i++)
{
scanf("%d", ptr); 
ptr++;
}
ptr = &arr[size - 1];
printf("\nElements of array in reverse 
order are :");
for (i = size - 1; i >= 0; i--)
{
printf("\nElement%d is %d : ", i,*ptr); 
ptr--;
}
getch();
}

OUTPUT:

Enter the size of array : 5
Enter 5 integers into array : 11 22 33 44 55 
Elements of array in reverse order are : 
Element 4 is : 55
Element 4 is : 44
Element 4 is : 33
Element 4 is : 22
Element 4 is : 11


Write a program using pointer to compare two strings.

#include<stdio.h>
void main()
{
 int flag=0;
 char str1[20],str2[40],*ptrs1,*ptrs2;
 clrscr();
 printf("enter first string");
 gets(str1);
 printf("enter second string");
 gets(str2);
 ptrs1=str1;
 ptrs2=str2;
while(*ptrs1 !='\0' && *ptrs2 != '\0')
 {
 if(*ptrs1 != *ptrs2)
 {
 flag = 1;
 break;
 }
 ptrs1++;
 ptrs2++;
 }
 if(flag==0)
 printf("strings are same");
 else
 printf("strings are different");
 getch();
}


Write a program using pointer to concate two strings.

#include<stdio.h>
#include<string.h>
void main()
{
 char str1[20],str2[20],*s1,*s2;
 clrscr();
 printf("enter the first string");
 gets(str1);
 printf("enter the second string");
 gets(str2);
 s1 = str1;
 s2 = str2;
// to reach at the end of string 1
 while(*s1!='\0')
 {
 s1++;
 }
 //to append string 2 at the end of string 1
 while(*s2 != '\0')
 {
 *s1 = *s2;
 s1++;
 s2++;
 }
 *s1='\0';
 puts(str1);
 getch();
}

Write a program using pointer to copy one string to another string.

#include<stdio.h>
#include<string.h>
void main()
{
 char str1[30],str2[30],*s1;
 int i=0;
 clrscr();
 printf("enter the first string");
 gets(str1);
 s1= str1;
while(*s1 != '\0')
 {
 str2[i] = *s1;
 s1++;
 i++;
 }
 str2[i]='\0';
 puts(str2);
 getch();
}


Write a program using pointer to read an array if integer and print element in reverse order.

#include<stdio.h>
#include<string.h>
void main()
{
 int i,n,*ar;
 clrscr();
 printf("enter the number of elements in 
array");
 scanf("%d",&n);
 ar=(int*) malloc(n * sizeof(int));
 for(i=0;i<n;i++)
 {
 printf("enter the element %d = " , i );
 scanf("%d",&ar[i]);
 }
for(i=n-1;i>=0;i--)
 {
 printf("element %d = %d\n",i,ar[i]);
 }
 getch();
}


Post a Comment

0 Comments