Topics

6/recent/ticker-posts

Pointers in C language

 

            Pointers
         


Definition: Pointer is a variable, which contains address of another variable in the memory. Pointer is one location in a memory, which contains address of another location in the memory. Pointers are unsigned data type ( since address is a unsigned type ).

 

Accessing address variable :

 

& ( ampersand )  à it is an address of operator to access address of variables.

 

Eg:

            int a;

 

                        &a  à address of variable a.

 

Program to print address of variables: 


Note: Address of first byte is an address of any variable.

Address of variable is unsigned data type . not depending on data type of the variable.

 

#include<stdio.h>

int main()

{

 int a=10;

 float b=20.5;

 char ch='a';

             printf("\n %d is stored at %u",a,&a);

            printf("\n %f is stored at %u ",b,&b);

            printf("\n %c is stored at %u ",ch,&ch);

 return 0;

 }

 


 





Accessing value of variable through the address:

 

Eg

            int  a=10;

 * --> value at

&à address of 

Value at ( address of  a) =10

*(&a) Ã  10

 

Program to find the address of the given variables: 


#include<stdio.h>

#include<conio.h>

int main()

{

 int a=10;

 float b=20.5;

 char ch='x';

             printf("\n %d  %d  %u ",a,*(&a),&a);

            printf("\n %f  %f  %u",b,*(&b),&b);

 printf("\n %c  %c  %u",ch,*(&ch),&ch);

 return 0;

}

 

 

Declaration of a pointer :

 

 

Syntax:

data_type  *pointer_name;

 

eg:

            int * ptr1;

 

here ptr1is a pointer variable, which can point ( refer ) to  integer  type  variable.

           

float * ptr2à it can point to only float variables.

 

Assigning address of variable to pointer: 

 

Eg1:

int a=10;

int *ptr1;

ptr1=&a; Ã  valid

ptr1 = a ; Ã  invalid

 

eg2:

 

float b=20.5;

float *ptr2;

ptr2=&b; Ã  valid

ptr2 = b Ã  invalid.

 

Program to print address of variables using pointer:

 

#include<stdio.h>

#include<conio.h>

int main()

{

 int a=10;

 float b=20.5;

 char ch='x';

 int *ptr1;

 float *ptr2;

 char *ptr3;

            ptr1=&a;

            ptr2=&b;

            ptr3=&ch;

 

             printf("\n%d  %u  %u " ,a,&a,ptr1);

            printf("\n %f %u %u ",b,&b,ptr2);

            printf("\n %c %u  %u ",ch,&ch,ptr3);

 return 0;

}

 

 

Initialization of a pointer: 


int a=10;

int *ptr1 = &a;

 

float b =20.5;

float *ptr2=&b;

 

char ch = ‘x’;

char * ptr3 = &ch;

 

Program to print address of variables using pointer:

#include<stdio.h>

#include<conio.h>

main()

{

 int a=10;

 float b=20.5;

 char ch='x';

 int *ptr1=&a;

 float *ptr2=&b;

 char *ptr3=&ch;

             printf("\n%d  %u  %u " ,a,&a,ptr1);

 printf("\n %f %u %u ",b,&b,ptr2);

 printf("\n %c %u  %u ",ch,&ch,ptr3);

 return 0;

}


 


Note: here the programs given as example are precompiled and runned.



Post a Comment

0 Comments