C-Tutorial: pointers

Latest

Showing posts with label pointers. Show all posts
Showing posts with label pointers. Show all posts

Wednesday, 5 October 2016

OPERATORS IN POINTERS

Wednesday, October 05, 2016 0
Pointer operators

There are two types of pointer operators in 'C'. Those are

1. Address operator(&):

·         To store the address of a variable into pointer variable
·         Control string is used to display the address as output is eiether %u or %p
%u --> Decimal format as output
%p --> Hexadecimal format as output

2. value at(*):

·         It is a special operator called indirect operator
·         It is used to access the value of the variable by using pointer

Accessing variable value through pointer:              

The value of a variable can be accessed through pointer variable using a unary operator ‘*’, usually known as indirection operator.  The operator refers to “value at the address in”.

Example:        *ptr    refers to value at the address in ptr

/* EXAMPLE PROGRAM TO DEMONSTRATE POINTERS CONCEPT */

main()
{
            int x,*ptr;
            clrscr();
            printf("\nAddress of x is:%u",&x);
            printf("\nAddress of ptr is:%u",&ptr);
            x=10;
            printf("\nx value using x:%d",x);
            ptr=&x;
            printf("\nValue in p:%u",ptr);
            printf("\nx value using ptr:%d",*ptr);

}
Read More

POINTERS, DECLARATION, INITILIZATION

Wednesday, October 05, 2016 0
POINTERS


            A pointer is a variable which holds the memory address of another variable. 

Pointer Declaration:              As similar to an ordinary variable, pointer variables must be declared before they are using.  A pointer variable is declared by preceding its name with an asterisk * symbol.  The symbol indicates that the variable is a pointer variable.  The general format of declaring a pointer variable is:

            Syntax:           datatype *ptrvariable;
Where,
Ø  ptrvariable is name of the pointer variable that follows same rules as a valid identifier.
Ø  ‘*’ tells the compiler that ptrvariable is a pointer variable.
Ø  datatype is the type of the data that the pointer is allowed to hold the address.

Example:        int *ptr1;
Here,   ptr1 is a pointer variable that can points to an integer type variable.

Example:        float *ptr2;
Here,   ptr2 is a pointer variable that can points to a float type variable.

            Example:        char *ptr3;
Here,   ptr3 is a pointer variable that can points to a character type variable.


Example:         int *ptr1;                     float *ptr2;                  char *ptr3;

                        2 bytes                         2 bytes                         2 bytes


                           ptr1                              ptr2                               ptr3

Note:   Any type of pointer occupies only 2 bytes of memory.  Since, pointer holds address of the variable which is always an unsigned integer.

Initializing Pointers:              Once a pointer variable has been declared, it can be initialized using an assignment operator as:

            Syntax:           ptrvariable = &ordinaryvariable;
           
Example:        ptr = &x;

Where, x is an ordinary variable.
Here, address of the variable x is stored in ptr.  With this, a link is formed from pointer variable to ordinary variable.

            Example:         int x,*ptr;
                                    x=10;
                                    ptr=&x;
           
A pointer variable can also be initialized at the time of its declaration itself.

                        Example:        int x, *ptr = &x;
Read More

Tuesday, 4 October 2016

Passing pointer to a function (or) pointer and functions

Tuesday, October 04, 2016 0
Passing pointer to a function (or) pointer and functions

Case1: pointers are often passed to a function as arguments call be reference mechanism.

/* EXAMPLE PROGRAM FOR CALL BY ADDRESS (or) CALL BY REFERENCE */

#include<stdio.h>
#include<conio.h>
void swap(int *,int *);
main()
{
            int x,y;
            clrscr();
            printf(“\n Enter Two Values =”);
scanf(“%d%d’,&x,&y);
            printf("\nBefore swapping the values are: ");
            printf("\nx :%d, y :%d",x,y);
            swap(&x,&y);
            printf("\n After swapping the values are: ");
            printf("\n x :%d, y:%d",x,y);
}
void swap(int *p, int *q)
{
            int temp;
            temp=*p;
            *p=*q;
            *q=temp;
}

Case2: C’ allows a pointer can store the address of a function.

Syn:  returntype(*pv)( );

We can call the function by using pointer variable.

Example program:
#include<stdio.h>
#include<conio.h>
int show(void);
main()
{
Int (*p)();
P=show;
(*p)();
Printf(“%u”,show);
}
int show()
{
printf(“address of show is: “);
}



Case 3: pointers can be passed as an argument from one function to another function. (or) ‘C’ allows a pointer to pass one function to another function as an argument.

Syntax:    returntype   function_name (pointer to function  (other arguments));

Example program:
int add(int,int);
int process(int (*) (int,int));
main()
{
int x;
clrscr();
x=process(add);
printf(“sum of  numbers %d”,x);
}
int process(int (*p) (int a,int b))
{
int c,a=20,b=10;
c=(*p)(a,b);
return c;
}
int add(int a, int b)
{
return  a+b;

}
Read More

INDEXING POINTERS

Tuesday, October 04, 2016 0
INDEXING POINTERS

                        When an array is declared, the compiler allocates a base address and sufficient amount of storage space for storing all the elements of the array in successive memory locations.  The name of the array is the beginning address (first element index 0) of the array, called the base address.  So, that the array name is referred to as an address constant.

            Example:        int x[5] = {10,20,30,40,50};
           
Here,
                        x = &x[0] = &x   all are referred to the address location 1000.

With the relationship between the array and pointer, array subscripts can also be defined in terms of pointer arithmetic operations which are known as indexing pointers.

For single dimensional arrays,

            int x[3], i=0;

            &x[0] = x+0                            x[0] = *(x+0)
           
            i.e., &x[i] = x+i                       x[i] = *(x+i)

Similarly, for double dimensional arrays,

            &x[i][j] = (*(x+i)+j)                x[i][j] = *(*(x+i)+j)
                                                                       
            #include<stdio.h>
#include<conio.h>
main()
{
int i,a[5] = {10,20,30,40,50};
clrscr();
for(i=0;i<5;i++)
printf("a[%d] : %d",i,*(a+i));
getch();

}
Read More

free() function in dynamic memory allocation

Tuesday, October 04, 2016 0
free():  

The memory allocation done by malloc(), calloc() and realloc() functions at run time are released by invoking the function free() by the user explicitly.  The releasing of storage space becomes very important when the storage is space is limited.  The general form of free() function is:

            Syntax:           free(ptrvariable);


Read More

realloc() Function (Re Allocation Function)

Tuesday, October 04, 2016 0
realloc() Function (Re Allocation Function)         

Suppose previously allocated dynamic memory is not sufficient (or) memory is much larger than the requirement, in both cases some memory changes are required.  Memory changes can be done by using a library function called realloc() function.
           
realloc() function provides the altering the size of the memory allocation and the process is called reallocation of memory.  The general form of realloc() function is:

            Syntax:           ptrvariable = (casttype*)realloc(ptrvariable,newsize);

Where,
            ptrvariable is a pointer variable of type casttype.

Here,
            This function allocates a new memory space of the specified newsize and returns a pointer variable that represent first byte of the new memory block.  The newsize may be larger or smaller than the previous size.

Note:

             I.      The new memory block may or may not be begin at the same place as the old one.  In case, it is not able to find additional space in the same region, it will create the same in an entirely new region and moves the contents of the old block into the new block.
          II.      If the function is unsuccessful to allocate the memory space, it returns a NULL pointer and the original block is lost.

/* EXAMPLE PROGRAM FOR REALLOC() FUNCTION */
main()
{
            int *p,i,n;
            clrscr();
            printf("\nEnter how many numbers:");
            scanf("%d",&n);
            p=(int*)malloc(n*sizeof(int));
            p=(int*)realloc(p,(n+2)*sizeof(int));
            printf("\nEnter %d Elements:",n+2);
            for(i=0;i<n+2;i++)
            scanf("%d",p+i);
            printf("\nArray Elements Are:");
            for(i=0;i<n+2;i++)
            printf("      %d",*(p+i));

}
Read More

Calloc() function (Contiguous Memory Allocation Function)

Tuesday, October 04, 2016 0
 Calloc() function (Contiguous Memory Allocation Function): 

  • calloc() function is another memory allocation function used for dynamic memory allocation for storing derived data types such as arrays and structures etc.,
  •  malloc() function allocates a single block of storage space, whereas calloc() function allocates multiple blocks of storage space with each of same size and all locations are initialized with ‘0’.  The general form of calloc() function is:


            Syntax:           ptrvariable = (casttype*)calloc(n,elesize);

Where,
            ptrvariable is a pointer variable of type casttype.
            n represents number of blocks.
            elesize represents block size.

            All blocks are initialized with ‘0’ and a pointer of the first block is returned.  If there is not enough space to allocate, then it returns a NULL pointer.


Example:        int *X;

                        X = (int*)calloc(5,sizeof(int));

For this, memory allocation will be:

                                                    10 BYTES


/* EXAMPLE PROGRAM FOR CALLOC() FUNCTION */

main()
{
            int *p,i,n;
            clrscr();
            printf("\nEnter how many numbers:");
            scanf("%d",&n);
            p=(int*)calloc(n,sizeof(int));
            printf("\nEnter %d Elements:",n);
            for(i=0;i<n;i++)
            scanf("%d",p+i);
            printf("\nArray Elements Are:");
            for(i=0;i<n;i++)
            printf("      %d",*(p+i));

}
Read More