You are on page 1of 15

Problem Solving And Programming CA5103 Unit-5 Pointer

A Pointer is a variable that holds a memory address .This address is the location of another object in memory. For Example, if one variable contains the address of another variable, the first variable is said to point to the second.

VIM
1003

MA
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009

VIM- Variable In Memory. MA- Memory Address. Pointer Declaration


A pointer declaration consists of a base type, an*, and the variable name. The general form for declaring a pointer variable is

Type *name;
Where type is the data type of the pointer and may be any valid type. The name of the pointer variable is specified by name.

The base type of the pointer defines the type of object to which the pointer will point. For Example, when you declare a pointer to be of type int*, the complier assumes that any address that it holds points to an integer. Pointer Expression An Expression may contain pointer which are referred to values. a. S=*aptr+*bptr; b. *p=*xp**xy; Example #include<stdio.h> Main() { int i,j=25; int *pi,*pj=&j; *pj=j+5; i=*pj+5; pi=pj; *pi=i+j; }

Special aspects of Pointer Expression Pointer Assignment. Pointer Conversion. Pointer Arithmetic. Pointer Assignment We can use a pointer on the right hand side of an assignment statement to assign its value to another pointer. When both pointers are of same type, this is straight forward. Example int *p1,*p2; int x=100; p1=&x; p2=p1; Pointer Conversion One type of pointer can be converted into another type of pointer. There are two general categories of conversion. They are Implicit Conversion. Explicit Conversion. Implicit Conversion In C, it is permissible to assign a void* pointer to any other type of pointer. It is also permissible to assign any other type of pointer to a void* pointer. A void* pointer is called a generic pointer. The void* Pointer is used to specify a pointer whose base type is unknown. The void* type allows a function to specify a parameter that is capable of receiving any type of pointer argument without reporting a type mismatch. It is also used to refer to raw memory when the semantics of that memory are not known. No explicit cast is required to convert to or from a void* pointer. Explicit Conversion Except for void*. all other pointer conversion must be performed by using an explicit cast. Pointer Arithmetic There are only two arithmetic operation that can be performed on pointer are Addition. Subtraction. For Example, P++; Each time a pointer is increment, it points to the memory location of the next element of its base type. P--; Each time a pointer is decremented, it points to the location of the previous element.

Pointer Operator There are two pointer operators. They are * and & * Operator- [Indirection] It is a unary operator that returns the value located at the address. It is also called the dereference operator. &Operator- [Direction] It is a unary operator that returns the memory address of its operand. Example int s=50,*p; p=&s; printf(%d,*p);//return value of the operand. printf(%p,p);//return the address of the operand. Multiple Indirection When the pointer points to another pointer that points the target value t. This situation is called multiple indirection, or pointer to pointer. A variable that is a pointer to a pointer must be declared by placing an additional asterisk In front of the variable name. Example int **ptr;//pointer to pointer

address Single Indirection

value

address

address Multiple Indirections

value

To access the target value indirectly pointed to by a pointer to a pointer, we must apply the asterisk operator twice. For Example, #include<stdio.h> int main() { int x,*p,**q; x=10;

p=&x; q=&p; printf(%d,**q); return 0; } Output 10 Pointer to Function Function A Function is a self contained block of program statements that performs a particular task. It is often defined as a section of a program performing a specific job. Passing Argument to Function In C Language, there are two ways to pass argument to the subroutine. They are Call By Value. Call By Reference. Call By Value In this method, the value of the actual argument is copied into the formal argument of the subroutine. In this case, changes made to the parameter have no effect on the argument. Call By Reference In this method, the address of the actual argument is copied into the formal argument of the subroutine. Inside the subroutine, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument. Function Pointers Like variables, function is also having address in memory. Normally, when a function is complied into an executable program, memory is reserved for the functions executable code to reside in memory at runtime. And when the program runs, the function loads into memory somewhere. The address of a function can be easily obtained by using a function name without the parentheses. The general format to declare a pointer to a function is as follows. Return data_type(*function-name)(argument-list) Where Return data_type is the return data type. Function name is the name of the pointer to create. Argument-list is the list of function arguments. For example the declaration, void (*fptr)(void); represents a pointer to a function that has a return type void, and takes no arguments. A function pointer can be assigned to another function that has the same format.

For example
#include<stdio.h> void main() { void message(); void (*fptr)(); fptr=message;//Assign address of the function printf("\nAddress of the message function is %p",fptr); fptr();//invokes the function message() } void message() { printf("\nHai, My Dear Friend...."); } Output Address of the message function is 02A7 Hai, My dear friend... Function with variable number arguments There are two ways to pass variable number of argument to the function. They are Function accept pointer to an array. Declare Function with variable length argument. To use a function with variable number of arguments, the following functions are needed and are avaliable in <stdarg.h> Function Name va_list va_start va_arg va_end Example #include<stdarg.h> #include<stdio.h> int sum(int no,...) { int sum1=0,x; va_list mylist; va_start(mylist,no); for(x=0;x<no;x++) sum1+=va_arg(mylist,int); va_end(mylist); return sum1; } void main() { printf("\nSum of 3 Arguments %d",sum(3,10,20,30)); printf("\nSum of 3 Arguments %d",sum(5,4,100,20,30)); } Description To store the list of arguments. To initialise the list. To return the next argument in the list. To clean up the variable argument list.

Function returning pointer Example

#include<stdio.h> #include<string.h> #include<conio.h> #include<stdlib.h> char *stringadd(char *,char *); void main() { char st1[20],st2[20],*ptr; clrscr(); puts("Enter first string"); fflush(stdin); gets(st1); puts("Enter Second string"); fflush(stdin); gets(st2); ptr=stringadd(st1,st2); printf("\n Output concatenated string is:%s",ptr);

} char *stringadd(char *s1,char *s2) { char *tempstr; tempstr=(char *)malloc(sizeof(strlen(s1)+strlen(s2))); strcpy(tempstr,s1); strcat(tempstr," "); strcat(tempstr,s2); return tempstr; }

Advantage of Pointer Pointer allows function to modify their calling arguments. Pointer supports dynamic allocation. Pointer can improve the efficiency of certain routines. Pointer provides support for dynamic data structure, such as binary trees and linked lists. Pointer save memory. Accessing a Pointer variable When a pointer variable declared as a pointer to a structure, the member of the structure can be accessed by using the arrow operator as pointer_to_structure member_name; Ways to access member Struct account cust,*pc; Pc=&cust;

pcacc_no; (*pc).acc_no; (&cust)acc_no; Dynamic Memory Allocation Dynamic memory allocation refers to the method of allocating a block of memory and releasing it when the memory is not required at the time of running the program. A block of memory can be used to store values of simple or subscripted variables, and a block of memory can be accessed using a pointer. Following are the functions used in dynamic memory allocation, and these functions are available in the header file <alloc.h>. Malloc() Function Malloc() function is used to allocate a single block of memory to store values of specific datatype .it also assigns the address of the first bytes of the allotted space to a pointer. It also assigns the address of the first byte of the allotted space to a pointer. It has the following form ptr=(type*)malloc(size); where ptr refers to pointer variable. type refers to the datatype to be stored in memory. size refers to number of bytes to be allotted. Example int *mptr; mptr=(int*)malloc(100); mptr=(int*)malloc(50*sizeof(int)); The allotted space can be used to store 50 int type values, and this block of memory can be accessed by the pointer mptr of the same type. calloc() Function calloc() function is used to allocate memory in multiple block of same size during the program execution. The space allotted is used to store values of an array or structure. This function assigns the address of the first byte of the allotted space to a pointer. It also assigns 0 as the intial value for all bytes in the block of memory. It has the following form ptr=(type *)calloc(n.m); where ptr refers to pointer variable. type refers to the data type to be stored in memory. n refers to number of blocks to be allotted m refers to number of bytes in each block of memory. Example float *xp; xp=(float *)calloc(50,4); xp=(float *)calloc(50,sizeof(float));

The allotted space may be used to store 50 float type values and are accessed by the pointer the same type. realloc() Function realloc() function is used to modify or reallocate the memory space which is previously allotted. This facilitate to increase or reduce the allotted space at a later stage in a program. It is just a reallocation of memory and the first byte address of the newly allotted space is assigned to the pointer. It has the following form ptr=realloc (ptr,size); where ptr refers to pointer variable of existing and new block. Size refers to number of bytes to be allotted newly. Example int *p; p=(int *)malloc(100); . . P=realloc(p,400); Now 400 byte is allocated to the program. free() function free() function is used to release the memory space which is allotted using malloc() or calloc() or realloc() function. It has the following form free(ptr); where ptr is the pointer which refers to the allotted space in memory. Example free(mptr); free(xp); When the functions are executed the allocated blocks of memory are released.

Comparison between Call by value and Call by Reference


Call by Value 1.This is the usual method to call a function in which only the value of the variable is passed as argument. 2. Any alteration in the value of the argument passed is local to the function and is not accepted in the calling program. 3.Memory location occupied by formal argument and actual arguments is different. 4.since a new location is created, this method is low. 5.There is no possibility of wrong data Call by Reference 1.In this method, the address of the variable is passed as argument. 2.Any alteration in the value of the argument passed is accepted in the calling program . 3.Memory location occupied by formal and actual arguments is same and there is a saving of memory location. Since the existing memory location is used through its address, this method is fast. 5.There is a possibility of wrong data

manipulation since the arguments are directly used in an expression.

manipulation since the addresses are used in an expression.

Pointer to Pointer Pointer has its own address space to store the address of the variable to which it is pointed. C allows to store the address of the pointer to another pointer, such a situation is knows as pointer to pointer. Example int *p1,**p2,***p3,v=25; p1=&v; p2=&p1; p3=&p2;

Representation of pointer to pointer to pointer


P3 Address of P2 P2 Address of P1 P1 Address of v V 25

Void Pointer Pointer can also be declared as void type. Void pointers cannot be dereferenced without explicit type conversion, because being void the complier cannot determine the size of the object that the pointer points to. Example
#include<stdio.h> #include<conio.h> int p; float d; char c; void *pt=&p; void main(void) { clrscr(); *(int *)pt=12; printf("\np=%d",p); pt=&d; *(float*)pt=5.4; printf("\nr=%f",d); pt=&c; *(char*)pt='s'; printf("\nc=%c",c); }

Output P=12 R=5.4 C=S Pointers and Arrays An array name by itself is an address or pointer. It points to the address of the first element of an array. The elements of the array together with their addresses can be displayed by using the array name itself. Array elements are always stored in contiguous memory locations. Pointer And One-Dimensional Arrays In C, when a one dimensional array is declared, the array name denotes the address of the zeroth element in an array. For example, in the declaration float fnum[15],fptr; fptr=fnum; the array name fnum denotes the address of the zeroth array variable fnum[0] which points the value of float data type. Expression using pointer addressing fnum or fnum+0 *(fnum+0) Expression using subscript addressing &fnum[0] fnum[0] Action Returns address of fnum[0] Returns valueof fnum[0]

A pointer is a variable whereas an array name itself is a fixed address and it is not a variable. A pointer must be initialized but an array name must not be initialized as it is an address only. Example fptr++; ++fptr; fptr--; --fptr; are possible in pointer variable, when the base address of the array is assigned to it but not possible by using array name. Pointers And Multidimensional Array A multidimensional array is a array of arrays. It can be accessed in many different ways. The array name of the multidimensional array also denotes the address of the zeroth element in that array. Address of Multi dimensional array &a[i][j]or *(a+i)+j or a[i]+j &a[0][0]or a[0] or *a or a Value of multi dimensional array *(*(a+i)+j) or *(a+i) [j]or*&a[i][j] or *(a[i]+j) *&a[0][0] or *a[0] or **a or

a[0][0] Array of Pointer Array of Pointer stores group of individual variable address or array of variable address in a continuous memory location. It is similar to pointer variable. The format for the declaration of an array of pointer is data_type *array_name[size]; Example float *a[10]; allocates memory for 10 pointer variable that holds address of the 10 float type variable. Pointer to an array Array elements are stored in consecutive memory locations. Two dimensional array elements are stored row by row. In C, it is possible to define a two dimensional array as a pointer a group of consecutive one-dimensional array as data-type (*arrayname)[size]; instead of data-type arrayname[size1][size2]; The size in the declaration of a pointer to an array represents the number of elements in each row.

Storage Representation of a pointer to an array


Y[0]

Y[1]

Y[ An array of pointers and pointer to an arrays may also be used for representing three dimensional and higher dimensional arrays using the pointer to pointer concepts. Pointer to Structure Pointer is used to create structure dynamically. It is similar to pointer to an ordinary variable. Example
#include<stdio.h> #include<conio.h> #include<math.h> #include<stdlib.h>

// Global Declaration struct stack { int data; struct stack *next; }; struct stack *top; // Function Protype int pop(); void push(int); int eval(int,char,int); // Main Module void main() { char in[20]; int i=0,op1,op2,t; int res; clrscr(); printf("\n\t\tEvaluation of Postfix Expression Using Stack\n"); printf("\n\t\t=============================================\n"); printf("\n\tEnter the Postfix Expression->"); scanf("%s",in); while(in[i]!='\0') { switch(in[i]) { case '^': case '/': case '*': case '+': case '-': op1=pop(); op2=pop(); res=eval(op1,in[i],op2); printf("%d\n",res); push(res); break; default: printf("Enter the value of %c->",in[i]); scanf("%d",&t); push(t); } i=i+1; } res=pop(); printf("The Result is %d",res); getch(); } // Insert Element void push(int item) { struct stack *temp; temp=(struct stack *)malloc(sizeof(struct stack)); temp->data=item;

} // Pick Element int pop() { int ch; struct stack *temp; temp=top; if(temp==NULL) printf("Stack Underflow"); else { ch=top->data; top=temp->next; } free(temp); printf("pop-%d\n",ch); return ch; } //Performing Operation int eval(int i1,char c2,int i2) { int r; switch(c2) { case '^': r=pow(i1,i2); break; case '/': r=i1/i2; break; case '*': r=i1*i2; break; case '+': r=i1+i2; break; case '-': r=i1-i2; break; default: r=0; } return r; }

if(top==NULL) { temp->next=NULL; top=temp; } else { temp->next=top; top=temp; } printf("push-%d\n",temp->data);

Output Enter the Postfix Expressionabc+de+f*+g/+ Enter the value of a b c d e f g 1 2 2 2 2 5 48 The Result is 3 Pointer to String An array of character terminated with \0 character is known as string. Example char sam[20]; char *s; Once the string has been defined it cannot be initialized to another set of characters. But char pointer allows this initialized. For Example char sam[20]=welcome; char chk[20],*c; chk=sam;//error c=sam;//possible Example

1)//

Program to find length of the string #include<stdio.h> #include<conio.h> void main() { char str[20],*s; int p=0,q=0; clrscr(); printf("Enter String-->"); gets(str); s=str; while(*s!='\0') { printf("%c",*s); p++; s++; if(*s==32)//ASCII Value of space is 32 q++; } printf("Length of the string including spaces:%d ",p); printf("Length of the string excluding space:%d",p-q); }

2)

// combining two string #include<stdio.h> #include<conio.h>

void main() { char *s1,*s2; int i=0,j=0; clrscr(); printf("\nEnter the First String-->"); gets(s1); printf("\nEnter the second string-->"); gets(s2); while(*(s1+i)!='\0') i++; while(*(s2+j)!='\0') { *(s1+i)=*(s2+j); i++; j++; } *(s1+i)='\0'; printf("\n Concatenated String is %s ",s1); getch(); }

You might also like