Pointer

Pointer
Pointer is a special variable that stores the address of another variable of same type.

Pointers are used in C program to access the memory and manipulate the address. . The general form of a pointer variable declaration is:

type *var_name;

Here, type is the pointer's data 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 like

 int *ptr                    or        int * ptr                    or        int * ptr
float *fptr
char *cptr

Whenever a variable is declared, system will allocate a location to that variable in the memory, to hold value. This location will have its own address number.
Let us assume that system has allocated memory location 8094F for a variable a.
int a=10;

a
Name of variable
10
Value stored in variable
8094F
Address of variable a

We can access the value 10 by either using the variable name a or the address 8094F. Since the memory addresses are simply numbers they can be assigned to some other variable. The variable that holds memory address are called pointer variables. To use pointer we have to write

int *ptr;                    //integer pointer
ptr=&a;                    //ptr assigned address of a

Here &a gives the address of the variable a to the pointer ptr, & is called reference operater or address of operator

ptr
Name of pointer
8094F
Value of ptr which is address of a
9342
Address of ptr

*ptr creates the pointer of type integer and &a gives the address of variable a,
So here ptr=&a means ptr is storing address of variable a
Pointer ptr is pointing the address of variable a so *ptr can also retrieve the value stored at that address.
So *ptr will also point the value 10 which is stored at the address 8094F(address of a)

Initialization of Pointer variable
Pointer Initialization is the process of assigning address of a variable to pointer variable. Pointer variable contains address of variable of same data type. In C language address operator & is used to determine the address of a variable. The & (immediately preceding a variable name) returns the address of the variable associated with it.

int a = 10 ;
int *ptr ;        //pointer declaration
ptr = &a ;        //pointer initialization
or,
int *ptr = &a ;

NULL Pointers in C
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>
void main ()
{
   int  *ptr = NULL;
   printf("The value of ptr is : %x\n", ptr  );
}

When the above code is compiled and executed, it produces the following result:
The value of ptr is 0


Rules of Pointer
1.       Pointer can be assigned the address of another variable
2.      Pointer variable can assigned the value of another pointer variable
3.      Pointer can be initialized NULL or zero value ( Null pointer, Pointing Nothing)
4.      Pointer can be prefixed or postfixed with increment or decrement operators
5.      We can add or subtract integer value from pointer
6.      Two pointer variable cannot be added


Pointers and Array (Pointer to an Array)
When array is declared, compiler allocates the memory to store the elements of array.
The address of the first element of array is called base address. For example

int x[5]={10,20,30,40,50};

Suppose the base address of x is 1024. Integer requires 2 bytes and five elements of array will be stored as

10
20
30
40
50
Elements:       X[0]                x[1]                  x[2]                 x[3]                 x[4]
Address:         1024                1026                1028                1030                1032
int *ptr;
ptr=&x[0]   or        ptr=x;                      
//pointer pointing the base address (address of first element &x[0] of  an array x) of array

Now we can access any element of an array using ptr++ to move from one element to another.
So initially
ptr=&x[0]      //here value=10 address 1024
ptr++              //incrementing pointer
now pointer will point
ptr=&x[1]       //now value20 address 1026
and thus we can move ahead till last value of an array

int i;
int x[5] = {1, 2, 3, 4, 5};
int *ptr = x;  // same as int*ptr = &x[0]
for (i=0; i<5; i++)
{
             printf("%d", *ptr);
             ptr++;
}

Pointer and Character String
Using char array we are creating string like
char str[10]=”india”;
Where compiler automatically insert the null character ‘\0’ at the end of string.
Similarly pointer can also be used to create string. Pointer variable of string type are used to create string

            char *str=”india”;
This creates the string and pointer str now points to the first character of “india”
Here str is pointer to the string and also the name of string

i
n
d
i
a
\0
           

We can also assign value at run time
            char *str;
            str=”india”;
and we can print the string using printf of puts functions like
            printf(“%s”,str);               or                    puts(str);
Since string is terminated by the null character the statement
            while(*str !=’\0’)
is true until the en d of string is found.

 Array of Pointer (pointer to multi-dimension array)
Pointer can handle table of string more batter than normal character array.
For an example array of string like
char name[3][20];
will create the name table containing 3 row and 20 columns which can store 3 names upto length 20 only and total storage require for this array is 60 bytes
Like this
char  name={“surat”, ”baroda”, ”pune”};
Array elements will be stored like

s
u
r
a
t
\0














b
a
r
o
d
a
\0













p
u
n
e
\0
















In above approach memory wastage is more

We can make pointer to string of flexible length like
            char *name[3]= {“surat”, ”baroda”, ”pune”};
 It will declare name as an array ofthree pointers to character, each pointer pointing a particular name as
            name[0]=”surat”
            name[1]=”baroda”
            name[2]=”pune”

This declaration allocated like
s
u
r
a
t
\0

b
a
r
o
d
a
\0
p
u
n
e
\0


And it will be allocated 18bytes, and it will use less memory compared to normal array variable.

Explain call by value and call by reference with example.
There are two ways that a C function can be called from a program. They are,
  1. Call by value
  2. Call by reference

1. Call by value:
  • In call by value method, the value of the variable is passed to the function as parameter.
  • The value of the actual parameter cannot be modified by formal parameter.
  • Different Memory is allocated for both actual and formal parameters. Because, value of actual parameter is copied to formal parameter.
Note:
  • Actual parameter – This is the argument which is used in function call.
  • Formal parameter – This is the argument which is used in function definition
//Example of Call by Value
#include <stdio.h>
#include<conio.h>
void swapval(inta,int b);
void main()
{
            inta,b;
            clrscr();
            a=10;
            b=20;
            printf(“\nValues before swap a=%d and b=%d”,a,b);
            swapval(a,b);
            getch();
}
void swapval(inta,int b)
{
            inttmp;
            tmp=a;
            a=b;
            b=tmp;
            printf(“\nValues after swap a=%d and b=%d”,a,b);

}

2. Call by reference: (Pointer as Function Argument)
  • In call by reference method, the address of the variable is passed to the function as parameter.
  • The value of the actual parameter can be modified by formal parameter.
  • Same memory is used for both actual and formal parameters since only address is used by both parameters.
//Example of Call by Reference
#include <stdio.h>
#include<conio.h>
void swapval(int*a,int*b);
void main()
{
            inta,b;
            clrscr();
            a=10;
            b=20;
            printf(“\nValues before swap a=%d and b=%d”,a,b);
            swapval(&a,&b);
            getch();
}
void swapval(int*a,int*b)
{
            inttmp;
            tmp=*a;
            *a=*b;
            *b=tmp;
            printf(“\nValues after swap a=%d and b=%d”,*a,*b);

}
  

Function returning Pointer
A function can also return a pointer to the calling function. In this case you must be careful, because local variables of function doesn't live outside the function, hence if you return a pointer connected to a local variable, that pointer be will pointing to nothing when function ends.
#include <stdio.h>
#include <conio.h>
int* larger(int*, int*);
void main()
{
             int a=15;
             int b=92;
             int *p;
             clrscr();
             p=larger(&a, &b);
             printf("%d is larger",*p);
             getch();
}

int* larger(int *x, int *y)
{
             if(*x > *y)
                          return x;
             else
                          return y;
}



Arrays
Structures
1. An array is a collection of related data elements of same type.
1. Structure can have elements of different  types
2. An array is a derived data type
2. A structure is a user-defined data type
3. Any array behaves like a built-in data types. All we have to do is to declare an array variable and use it.
3. But in the case of structure, first we have to design and declare a data structure before the variable of that type are declared and used.
4. Array elements are accessed by index number
4. Structure elements are accessed by name and . operator
int ar[10];
//Declare array and array variable
struct book{
            int id,
            char name[20];
}bk1;
//book is a structure and bk1 is structure variable


 Pointer and Structure  
Like we have array of integers, array of pointer etc, we can also have array of structure variables. And to make the use of array of structure variables efficient, we use pointers of structure type. We can also have pointer to a single structure variable, but it is mostly used with array of structure variables.

#include<stdio.h>
#include<conio.h>
struct book
{
            int id;
            char name[20];
};
void main()
{
            struct book b1;
            struct book *bptr;
            clrscr();
            bptr=&b1;

            printf("insert id");
            scanf("%d",&bptr->id);                     //Accessing Structure Members
            printf("insert name");
            scanf("%s",bptr->name);                  //Accessing Structure Members
            printf("\nData");
            printf("\n%d %s",bptr->id,bptr->name);    //Accessing Structure Members

            getch();
}


To access members of structure with structure variable, we used the dot . operator. But when we have a pointer of structure type, we use arrow -> to access structure members.




0 comments:

Post a Comment