Ex. No: 3.1 Introduction to Pointers Aim To learn the concept of pointers in C programs. Data for a variable is stored at some memory location. Address and Data are two sides an variable. For instance x =10 is represented as Variable Data Address x 3221216948 The address of a variable can be obtained using& operator known asreference operator. The variable's value can be obtained using the dereference operator *. Pointer Variable A Pointer variable or a pointer is a special variable that holds the address of another variable. Pointer variable are distinguished from other variables by having an asterik (*) prefixed in the declaration statement. i nt x, *i pt r ; A pointer variable is a derived data type based on either standard, derived or user-defined data type. A pointer variable can be made to point any variable of its base type by assigning the variable's address to the pointer. For instance, an integer pointer can point to an integer variable only. A pointer variable is allocated 2 bytes irrespective of the data type it points. pt r = &x; / * Assi gni ng addr ess X t o poi nt er */ Value of the variable pointed to can be accessed by applying the dereference operator pr i nt f ( " Val ue of t he var i abl e poi nt ed t o %d", *pt r ) ; A pointer of type void is referred to asgeneric pointer i.e. it can point to any data type. Since pointer variables hold address, integers could be added or subtracted to yield another address. A pointer that holds the address of another pointer variable is known aspointer-to-pointer. Result Thus C programs using pointers were executed. 10 C Programming GE2155Computer Practice II cseannauniv.blogspot.in Vijai Anand SK 3.1.AReference and Dereference operator Program (refderef.c) / * Dat a and addr ess */ #i ncl ude <st di o. h> mai n( ) { i nt x; x=10; pr i nt f ( "Val ue of x i s %d", x) ; pr i nt f ( "\ nAddr ess of x i s %u" , &x) ; pr i nt f ( "\ nVal ue of x i s %d\ n" , *( &x) ) ; } Output [ vi j ai @l ocal host poi nt er ] $ gcc refderef.c [ vi j ai @l ocal host poi nt er ] $ ./a.out Val ue of x i s 10 Addr ess of x i s 3221216948 Val ue of x i s 10 3.1.BPointer variables Program (ptrvar.c) / * Poi nt er var i abl es */ # i ncl ude<st di o. h> mai n( ) { i nt x, y, *i pt r ; f l oat *f pt r ; x = 125; i pt r = &x ; / * i pt r poi nt s t o x */ y = 23; / * f pt r = &y; i s er r oneous */ pr i nt f ( "X val ue i s %d and st or ed at %u\ n", x, &x) ; pr i nt f ( "Y val ue i s %d and st or ed at %u\ n", y, &y) ; pr i nt f ( "\ nI nt poi nt er hol ds t he addr ess %u\ n", i pt r ) ; pr i nt f ( "Aceesi ng val ue t hr u poi nt er : %d\ n", *i pt r ) ; i pt r = &y; / * i pt r poi nt s t o y */ pr i nt f ( "\ nI nt poi nt er now hol ds t he addr ess %u\ n" , i pt r ) ; pr i nt f ( "Accessi ng val ue t hr u poi nt er : %d\ n" , *i pt r ) ; pr i nt f ( "\ nSi ze of i nt poi nt er : %d byt es", si zeof ( i pt r ) ) ; pr i nt f ( "\ nSi ze of f l oat poi nt er : %d byt es", si zeof ( f pt r ) ) ; pr i nt f ( "\ n\ nAddr ess of mai n f unct i on i s %u\ n", mai n) ; } C Programming GE2155Computer Practice II cseannauniv.blogspot.in Vijai Anand SK Output [ vi j ai @l ocal host poi nt er ] $ gcc ptrvar.c [ vi j ai @l ocal host poi nt er ] $ ./a.out X val ue i s 125 and st or ed at 3221216452 Y val ue i s 23 and st or ed at 3221216448 I nt poi nt er hol ds t he addr ess 3221216452 Aceesi ng val ue t hr o poi nt er : 125 I nt poi nt er now hol ds t he addr ess 3221216448 Accessi ng val ue t hr o poi nt er : 23 Si ze of i nt poi nt er : 4 byt es Si ze of f l oat poi nt er : 4 byt es Addr ess of mai n f unct i on i s 134513448 3.1.CPointertoPointer Program (ptrtoptr.c) / * Poi nt er var i abl es */ # i ncl ude<st di o. h> mai n( ) { i nt x=12, *p1, **p2; f l oat z=8. 5; voi d *pt r ; / * Gener i c poi nt er */ pt r = &x ; / * pt r poi nt s t o x ( i nt ) */ pt r = &z; / * pt r poi nt s t o y ( f l oat ) */ p1 = &x; p2 = &p1; / * Poi nt er t o poi nt er */ pr i nt f ( "X val ue i s %d and st or ed at %u\ n", x, &x) ; pr i nt f ( "\ nPoi nt er hol ds t he addr ess %u\ n", p1) ; pr i nt f ( "Aceesi ng val ue t hr u poi nt er : %d\ n", *p1) ; pr i nt f ( "Poi nt er i s st or ed at l ocat i on : %u\ n", &p1) ; pr i nt f ( "\ nPoi nt er - t o- poi nt er hol ds t he addr ess %u\ n", p2) ; pr i nt f ( "Accessi ng val ue t hr u pt r - t o- pt r : %d\ n", **p2) ; pr i nt f ( "\ nSi ze of pt r - t o- pt r : %d byt es\ n", si zeof ( pt r ) ) ; } Output [ vi j ai @l ocal host poi nt er ] $ gcc ptrtoptr.c [ vi j ai @l ocal host poi nt er ] $ ./a.out X val ue i s 12 and st or ed at 3221220804 Poi nt er hol ds t he addr ess 3221220804 C Programming GE2155Computer Practice II cseannauniv.blogspot.in Vijai Anand SK Aceesi ng val ue t hr u poi nt er : 12 Poi nt er i s st or ed at l ocat i on : 3221220800 Poi nt er - t o- poi nt er hol ds t he addr ess 3221220800 Accessi ng val ue t hr u pt r - t o- pt r : 12 Si ze of pt r - t o- pt r : 4 byt es 3.1.DAddition using pointers Program (ptradd.c) / * Addi t i on oper at i ons usi ng poi nt er s */ #i ncl ude<st di o. h> mai n( ) { i nt a, b, c; i nt *pa, *pb; pa=&a; pb=&b; pr i nt f ( "Ent er val ues f or A and B : ") ; scanf ( "%d%d", &a, &b) ; c = *pa + *pb; pr i nt f ( "Sum= %d\ n" , c) ; } Output [ vi j ai @l ocal host poi nt er ] $ gcc ptradd.c [ vi j ai @l ocal host poi nt er ] $ ./a.out Ent er val ues f or A and B : 4 6 Sum= 10 3.1.EBasic Calculator Program (ptrcalc.c) / * Ar i t hmet i c oper at i ons usi ng poi nt er s */ #i ncl ude<st di o. h> mai n( ) { i nt a, b, c; i nt *pa, *pb; char op; pa=&a; pb=&b; pr i nt f ( "Basi c Cal cul at or ") ; pr i nt f ( "\ n + Addi t i on") ; pr i nt f ( "\ n - Subt r act i on") ; C Programming GE2155Computer Practice II cseannauniv.blogspot.in Vijai Anand SK pr i nt f ( "\ n * Mul t i pl i cat i on") ; pr i nt f ( "\ n / Quot i ent ") ; pr i nt f ( "\ n % Remai nder ") ; pr i nt f ( "\ n x Qui t ") ; pr i nt f ( "\ nEnt er oper at or : ") ; scanf ( "%c", &op) ; pr i nt f ( "Ent er t wo i nt eger s : ") ; scanf ( "%d%d", &a, &b) ; swi t ch ( op) { case ' +' : c = *pa + *pb; br eak; case ' - ' : c = *pa - *pb; br eak; case ' *' : c = *pa * *pb; br eak; case ' / ' : c = *pa / *pb; br eak; case ' %' : c = *pa %*pb; br eak; def aul t : exi t ( 0) ; } pr i nt f ( " %d %c %d = %d\ n", a, op, b, c) ; } Output [ vi j ai @l ocal host poi nt er ] $ gcc ptrcalc.c [ vi j ai @l ocal host poi nt er ] $ ./a.out Basi c Cal cul at or + Addi t i on - Subt r act i on * Mul t i pl i cat i on / Quot i ent %Remai nder x Qui t Ent er oper at or : + Ent er t wo i nt eger s : 12 23 12 + 23 = 35 C Programming GE2155Computer Practice II cseannauniv.blogspot.in Vijai Anand SK Ex. No: 3.2 Pointer Programming Aim To study the advantages of using pointers in C programming. Pointers & Function Arguments passed to functions arepass by value i.e., a copy of value of the actual arguments are passed. Therefore changes made to formal arguments are not reflected to actual arguments. However, to have the actual arguments modified during process by another function, then addresses of the arguments are passed, instead of values through pointers. This is known as pass by reference. Thus pointers facilitate multiple values to be returned by a function. Another use of pointers in function is that an address could be returned, known as return by reference. Pointers & Arrays Pointers can be used for efficient traversal of a given array. An array name by itself is a pointer to the first element in the array. The address of first element of array X can be expressed as either &X[0] or X. Thei+1 th element is termed as &X[i] or X+i. The value of i is referred to as offset. Thus a pointer can be assigned an array variable and array elements can be accessed by altering the offset. Similarly for two-dimensional array, X i+1,j+1 element could be accessed as * (* (X +i) +j). Pointers & Strings A string variable alternatively can be declared as a character pointer type since string is represented as an array of characters. The advantage is that length of the string need not be known in advance. Strings could be processed using character pointer. Pointers & Structures A pointer variable can be assigned a structure as any other type. The members of a structure are accessed using the indirect selection operator (- >). Self-referential structure is a structure where one of its members is a pointer to the structure itself. Such structures are used to implement data structures such as list and trees. Result Thus C programs using pointers were executed and its efficacy realized. C Programming GE2155Computer Practice II cseannauniv.blogspot.in Vijai Anand SK 3.2.APass by value & reference Program (passbyref.c) / * Pass by val ue and r ef er ence */ #i ncl ude <st di o. h> mai n( ) { i nt a, b; voi d swapval ( i nt , i nt ) ; voi d swapr ef ( i nt *, i nt *) ; pr i nt f ( "Ent er t he val ues of A and B : ") ; scanf ( "%d%d", &a, &b) ; swapval ( a, b) ; / * Cal l by val ue */ pr i nt f ( "\ nVal ues af t er Pass by Val ue\ n" ) ; pr i nt f ( "Val ue of A i s %d\ n", a) ; pr i nt f ( "Val ue of B i s %d\ n", b) ; swapr ef ( &a, &b) ; / * Cal l by r ef er ence */ pr i nt f ( "\ nVal ues af t er Pass by Ref er ence\ n") ; pr i nt f ( "Val ue of A i s %d\ n", a) ; pr i nt f ( "Val ue of B i s %d\ n", b) ; } voi d swapr ef ( i nt *x, i nt *y) / * Pass by r ef er ence */ { i nt t ; t = *x; *x = *y; *y = t ; } voi d swapval ( i nt a, i nt b) / * Pass by val ue */ { i nt t ; t = a; a = b; b = t ; } Output [ vi j ai @l ocal host poi nt er ] $ gcc passbyref.c [ vi j ai @l ocal host poi nt er ] $ ./a.out Ent er t he val ues of A and B : 12 23 Val ues af t er Pass by Val ue Val ue of A i s 12 Val ue of B i s 23 Val ues af t er Pass by Ref er ence Val ue of A i s 23 Val ue of B i s 12 C Programming GE2155Computer Practice II cseannauniv.blogspot.in Vijai Anand SK 3.2.BReturn by reference Program (retbyref.c) / *Ret ur n by r ef er ence*/ #i ncl ude <st di o. h> i nt * bi g( i nt * x, i nt * y) { i f ( *x > *y) r et ur n x; el se r et ur n y; } mai n( ) { i nt a, b; i nt *p; pr i nt f ( "Ent er t wo val ues : ") ; scanf ( "%d%d", &a, &b) ; p = bi g( &a, &b) ; pr i nt f ( "Bi ggest i s %d\ n" , *p) ; } Output [ vi j ai @l ocal host poi nt er ] $ gcc retbyref.c [ vi j ai @l ocal host poi nt er ] $ ./a.out Ent er t wo val ues : 3 7 Bi ggest i s 7 3.2.CSum of one-dimensional array Program (array1d.c) / * Poi nt er s and one- di mensi onal ar r ays */ #i ncl ude <st di o. h> mai n( ) { i nt i , n, sum=0; i nt x[ 25] , *p; pr i nt f ( "Ent er number of el ement s : ") ; scanf ( "%d", &n) ; pr i nt f ( "Ent er Ar r ay el ement s : ") ; f or ( i =0; i <n; i ++) scanf ( "%d" , &x[ i ] ) ; C Programming GE2155Computer Practice II cseannauniv.blogspot.in Vijai Anand SK p = x; / * p poi nt s t o ar r ay x */ f or ( i =0; i <n; i ++) { pr i nt f ( "x[ %d] = %d st or ed at %u\ n", i , *p, p) ; sum+= *p; p++; / * Addr ess i ncr ement ed poi nt s t o next el ement */ } pr i nt f ( "Sum= %d\ n ", sum) ; } Output [ vi j ai @l ocal host poi nt er ] $ gcc array1d.c [ vi j ai @l ocal host poi nt er ] $ ./a.out Ent er number of el ement s : 5 Ent er Ar r ay el ement s : 12 23 34 45 56 x[ 0] = 12 st or ed at 3221218368 x[ 1] = 23 st or ed at 3221218372 x[ 2] = 34 st or ed at 3221218376 x[ 3] = 45 st or ed at 3221218380 x[ 4] = 56 st or ed at 3221218384 Sum= 170 3.2.DDisplaying a two-dimensional array Program (2darray.c) / * Poi nt er s and 2- di mensi onal ar r ay */ #i ncl ude <st di o. h> mai n( ) { i nt a[ 3] [ 3] ={{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; i nt i , j ; f or ( i =0; i <3; i ++) { f or ( j =0; j <3; j ++) { pr i nt f ( "%4d" , *( *( a+i ) +j ) ) ; } pr i nt f ( "\ n") ; } } Output [ vi j ai @l ocal host poi nt er ] $ gcc 2darray.c [ vi j ai @l ocal host poi nt er ] $ ./a.out 1 2 3 4 5 6 7 8 9 C Programming GE2155Computer Practice II cseannauniv.blogspot.in Vijai Anand SK 3.2.EString copy using pointers Program (strcopy.c) / * Copy f r omone st r i ng t o anot her usi ng poi nt er s */ #i ncl ude <st di o. h> mai n( ) { voi d st r i ngcopy( char *, char *) ; char sr c[ 80] ; char des[ 80] ; pr i nt f ( "Ent er a st r i ng : ") ; get s( sr c) ; st r i ngcopy( des, sr c) ; pr i nt f ( "%s\ n", des) ; } voi d st r i ngcopy( char *d, char *s) { whi l e( *s) { *d = *s; s++; d++; } *d = ' \ 0' ; } Output [ vi j ai @l ocal host poi nt er ] $ gcc strcopy.c [ vi j ai @l ocal host poi nt er ] $ ./a.out Sel f - conquest i s t he gr eat est vi ct or y 3.2.FStudent Detail Program (studdetail.c) #i ncl ude<st di o. h> st r uct st udent { l ong r ol l no; char name[ 10] ; f l oat mar k; }; mai n( ) { st r uct st udent *pt r ; st r uct st udent s1; C Programming GE2155Computer Practice II cseannauniv.blogspot.in Vijai Anand SK pr i nt f ( "\ nEnt er st udent s r ol l no, name, mar k : ") ; scanf ( "%l d%s%f " , &s1. r ol l no, s1. name, &s1. mar k) ; pt r =&s1; pr i nt f ( "\ n\ t STUDENT DETAI L") ; pr i nt f ( "\ nRol l no\ t Name\ t \ t Mar k\ n") ; pr i nt f ( "%l d\ t %s\ t %. 2f \ n", pt r - >r ol l no, pt r - >name, pt r - >mar k) ; } Output [ vi j ai @l ocal host poi nt er ] $ gcc studdetail.c [ vi j ai @l ocal host poi nt er ] $ ./a.out Ent er st udent s r ol l no, name, mar k : 1032957 Adhi t han 10 STUDENT DETAI LS Rol l no Name Mar k 1032957 Adhi t han 10. 00 3.2.GEmployee Payroll Program (payroll.c) / * Payr ol l Gener at i on */ #i ncl ude <st di o. h> st r uct empl oyee { i nt empi d; char ename[ 15] ; i nt basi c; f l oat hr a; f l oat da; f l oat i t ; f l oat gr oss; f l oat net pay; }; mai n( ) { st r uct empl oyee emp[ 50] , *pt r ; i nt i , j , n; pr i nt f ( "Ent er No. of Empl oyees : ") ; scanf ( "%d" , &n) ; f or ( i =0; i <n ; i ++) { pr i nt f ( " \ nEnt er Empl oyee Det ai l s\ n") ; pr i nt f ( " Ent er Empl oyee I d : ") ; scanf ( "%d", &emp[ i ] . empi d) ; pr i nt f ( " Ent er Empl oyee Name : ") ; scanf ( "%s", emp[ i ] . ename) ; pr i nt f ( " Ent er Basi c Sal ar y : ") ; scanf ( "%d", &emp[ i ] . basi c) ; C Programming GE2155Computer Practice II cseannauniv.blogspot.in Vijai Anand SK } pt r =emp; f or ( i =0; i <n; i ++) { pt r - >hr a = 0. 02 * pt r - >basi c; pt r - >da = 0. 01 * pt r - >basi c; pt r - >i t = 0. 05 * pt r - >basi c; pt r - >gr oss = pt r - >basi c+pt r - >hr a+pt r - >da; pt r - >net pay = pt r - >gr oss - pt r - >i t ; pt r ++; } pt r =emp; pr i nt f ( "\ n\ n\ n\ t \ t \ t \ t XYZ & Co. Payr ol l \ n\ n") ; f or ( i =0; i <80; i ++) pr i nt f ( " *") ; pr i nt f ( " \ nEmpI d\ t Name\ t \ t Basi c\ t HRA\ t DA\ t I T\ t Gr oss\ t \ t Net Pay\ n\ n") ; f or ( i =0; i <80; i ++) pr i nt f ( " *") ; f or ( i =0; i <n; i ++) { pr i nt f ( "\ n%d\ t %- 15s\ t %d\ t %. 2f \ t %. 2f \ t %. 2f \ t %. 2f \ t %. 2f ", pt r - >empi d, pt r - >ename, pt r - >basi c, pt r - >hr a, pt r - >da, pt r - >i t , pt r - >gr oss, pt r - >net pay) ; pt r ++; } pr i nt f ( "\ n") ; f or ( i =0; i <80; i ++) pr i nt f ( " *") ; } Output [ vi j ai @l ocal host poi nt er ] $ gcc studdetail.c [ vi j ai @l ocal host poi nt er ] $ ./a.out Ent er No. of Empl oyees : 2 Ent er Empl oyee Det ai l s Ent er Empl oyee I d : 436 Ent er Empl oyee Name : Gopal Ent er Basi c Sal ar y : 10000 Ent er Empl oyee Det ai l s Ent er Empl oyee I d : 463 Ent er Empl oyee Name : Raj esh Ent er Basi c Sal ar y : 22000 XYZ & Co. Payr ol l ******************************************************************************** EmpI d Name Basi c HRA DA I T Gr oss Net Pay ******************************************************************************** 436 Gopal 10000 200. 00 100. 00 500. 00 10300. 00 9800. 00 463 Raj esh 22000 440. 00 220. 00 1100. 00 22660. 00 21560. 00 ******************************************************************************** C Programming GE2155Computer Practice II cseannauniv.blogspot.in Vijai Anand SK Ex. No: 3.3 Dynamic Memory Allocation Aim To achieve efficient memory utilization using dynamic memory allocation. Memory allocated using arrays is insufficient or abundant, thereby inefficient. To overcome this, memory could be allocated at run-time instead at compile time. The process of allocating memory at run time is known as dynamic memory allocation. C inherently does not have this facility but supports with memory management functions mal l oc, cal l oc andr eal l oc, which can be used to allocate and free memory usingf r ee during the program execution. The memory space located between program and local variable is available known as heap for dynamic allocation during the execution of the program. The size of heap keeps changing when program is executed due to creation and death of variables. Therefore it is possible to encounter memory overflow during dynamic allocation process. In such situations, the memory allocation functions will return a null pointer. malloc The malloc function reserves a block of memory of specified size and returns a pointer of type void containing the first byte of the allocated region. Thus it could be casted to any type of pointer. The allocated space contains garbage data. ptr =( cast-type*) mal l oc( bytesize) ; calloc calloc is another memory allocation function that is normally used to request multiple blocks of storage each of the same size and then sets all bytes to zero. ptr =( casttype*) cal l oc( blockcount, blocksize) ; free Compile time storage of a variable is allocated and released by the system in accordance with its storage class. With the dynamic runtime allocation, it is our responsibility to release the space when it is not required, using the free function. The release of storage space becomes important when the storage is limited. f r ee( ptr) ; realloc The memory allocated by using calloc or malloc might be insufficient or excess sometimes. In both the situations the memory size already allocated could be changed with the help of function realloc. This process is called reallocation of memory. ptr = r eal l oc( ptr, newsize) ; Result Thus memory requirements were allocated dynamically and released later. C Programming GE2155Computer Practice II cseannauniv.blogspot.in Vijai Anand SK 3.3.AMark aggregate Program (dynalloc.c) / * Dynami c Memor y Al l ocat i on usi ng mal l oc( ) */ #i ncl ude <st dl i b. h> #i ncl ude <mal l oc. h> #i ncl ude <st di o. h> mai n( ) { i nt n, i , *a; f l oat avg, sum=0; pr i nt f ( "Ent er t he No. of st udent s : ") ; scanf ( "%d" , &n) ; a = ( i nt *) mal l oc( n * si zeof ( i nt ) ) ; i f ( a == NULL) { pr i nt f ( "\ n memor y al l ocat i ons not possi bl e") ; exi t ( - 1) ; } pr i nt f ( "Ent er %d mar ks : ", n) ; f or ( i =0; i <n; i ++) { scanf ( "%d" , &a[ i ] ) ; } f or ( i =0; i <n; i ++) sum+= a[ i ] ; avg = sum/ n; pr i nt f ( "Aver age mar k : %. 2f \ n", avg) ; f r ee( a) ; } Output [ vi j ai @l ocal host poi nt er ] $ gcc dynalloc.c [ vi j ai @l ocal host poi nt er ] $ ./a.out Ent er t he No. of st udent s : 6 Ent er 6 mar ks : 56 67 78 89 90 98 Aver age mar k : 79. 67 C Programming GE2155Computer Practice II cseannauniv.blogspot.in Vijai Anand SK 3.3.BString Reallocation Program (strrealloc.c) / * Dynami c Real l ocat i on f or st r i ngs */ #i ncl ude <st di o. h> #i ncl ude <st dl i b. h> #i ncl ude <st r i ng. h> mai n( ) { char buf [ 80] , *message; put s( "Ent er t ext and pr ess r et ur n") ; get s( buf ) ; / * Get a st r i ng f r omt he user */ / * Al l ocat e t he i ni t i al bl ock and copy t he st r i ng t o i t . */ message = ( char *) mal l oc( st r l en( buf ) +1) ; st r cpy( message, buf ) ; pr i nt f ( "Cont ent st or ed i s : ") ; put s( message) ; / * Di spl ay t he message. */ pr i nt f ( "I ni t i al al l ocat i on : %d byt es\ n" , st r l en( message) ) ; put s( "Ent er t ext and pr ess r et ur n") ; get s( buf ) ; / * Get anot her st r i ng f r omt he user . */ / * I ncr ease al l ocat i on, t hen concat enat e e st r i ng t o i t */ message = ( char *) r eal l oc( st r l en( message) + 1) ; st r cpy( message, buf ) ; pr i nt f ( "Modi f i ed cont ent i s : ") ; put s( message) ; / * Di spl ay t he new message. */ pr i nt f ( "Real l ocat ed memor y : %d byt es\ n" , st r l en( message) ) ; f r ee( message) ; } Output [ vi j ai @l ocal host poi nt er ] $ gcc strrealloc.c / t mp/ ccgTf E9Z. o( . t ext +0x29) : I n f unct i on `mai n' : : t he `get s' f unct i on i s danger ous and shoul d not be used. [ vi j ai @l ocal host poi nt er ] $ ./a.out Ent er t ext and pr ess r et ur n Hi ! Cont ent st or ed i s : Hi ! I ni t i al al l ocat i on : 4 byt es Ent er t ext and pr ess r et ur n How r u? Modi f i ed cont ent i s : How r u? Real l ocat ed memor y : 8 byt es C Programming GE2155Computer Practice II cseannauniv.blogspot.in Vijai Anand SK 3.3.CAllocation for two dimensional array Program (2dcalloc.c) / * Dynami c al l ocat i on f or 2D ar r ay */ #i ncl ude <st di o. h> #i ncl ude <mal l oc. h> mai n( ) { i nt i , j , r ow, col , **pt r ; pr i nt f ( "Ent er r ow and col umn di mensi on : ") ; scanf ( "%d%d", &r ow, &col ) ; / * 2d ar r ay i s an ar r ay of poi nt er s */ pt r = ( i nt *) cal l oc( r ow, si zeof ( i nt ) ) ; f or ( i =0; i <r ow; i ++) pt r [ i ] = ( i nt *) cal l oc( col , si zeof ( i nt ) ) ; / * Di spl ay def aul t val ue 0 assi gned due t o cal l oc */ f or ( i =0; i <r ow; i ++) { f or ( j =0; j <col ; j ++) pr i nt f ( "%4d" , pt r [ i ] [ j ] ) ; pr i nt f ( "\ n") ; } f r ee( pt r ) ; } Output [ vi j ai @l ocal host poi nt er ] $ gcc 2dcalloc.c 2dcal l oc. c: I n f unct i on `mai n' : 2dcal l oc. c: 12: war ni ng: assi gnment f r omi ncompat i bl e poi nt er t ype [ vi j ai @l ocal host poi nt er ] $ ./a.out Ent er r ow and col umn di mensi on : 3 4 0 0 0 0 0 0 0 0 0 0 0 0 C Programming GE2155Computer Practice II cseannauniv.blogspot.in Vijai Anand SK Ex. No: 3.4 File Handling Aim To perform disk I/O using file handling Many application require information stored on auxillary storage device. Such information is stored permanently as a data file that allows to access and alter the information whenever necessary. Opening a File Prior to performing any activity of a file, the file should be opened. By opening a file, link between the program and the operating system is established. This link exists by means of a structure named FI LE, in header file stdio.h. Therefore, it is mandatory for programs pertaining to file should include <stdio.h>. When a request is made for a file to be opened, the operating system returns a pointer to the structure FILE. The pointer is declared as FI LE *fileptr; A file is opened using the standard function fopen(). The file to be opened is searched in the disk. If a file could not be opened, aNULL is returned. fileptr =f open(" filename" , "mode"); The file mode specifies the purpose of opening a file. Some of them are Mode Description r Open an existing file for reading only w Open a new file for writing only. If the file exists, its contents are destroyed a Open an existing file for appending. If the file doesn't exist, a new file is created The I/O operation is done using any of the following functions. getc & putc Thegetc function is used to read a character from the file opened in read mode and assigns it to a character variable. The getc will return anEOF marker when the end-of-file is reached. Thereafter reading is not possible. The putc function writes the character contained in the variable onto a file opened in write mode. The file pointer moves by one character position for every character I/O operation. charvar =get c( fileptr) ; put c( charvar, fileptr); getw & putw The getw and putw are integer oriented functions and are identical in nature to getc and putc. fgets & fputs Rather than single characters, to deal with stringsfgets andfputs are used in a similar manner. C Programming GE2155Computer Practice II cseannauniv.blogspot.in Vijai Anand SK fscanf & fprintf These functions handle mixed data. Care should be taken that the same format specifications is used for both read and write operation. fwrite & fread Applications might perform I/O as blocks of data, where each block is a fixed number of contiguous bytes. A block is generally represented as a structure. The library functions fread and fwrite are intended to be used in situations of this type and requires arguments namelyaddress, size andnumber of the data block. fread reads a block of data and assigns to a structure variable. fwrite writes contents of a structure variable onto the file. f r ead( &structvar, si zeof ( structvar) , 1, fileptr) ; f wr i t e( &structvar, si zeof ( structvar) , 1, fileptr) ; Random Access In random access any specified part of the file is pointed without the mundane reading through the file upto that point. This is achieved with the help of functions fseek, ftell and rewind available in the I/O library. Function Description f t el l Returns the number of bytes read or written r ewi nd Resets the file pointer to start of the file f seek Moves the file pointer to the desired byte f seek( fileptr, offset, position) ; position can take values 0, 1 or 2 indicatingbegining, current position, andend of the file respectively fclose A file should be closed when all operation on it have been completed. This ensures all information associated with the file is flushed out of the buffers and all links to the file broken. A file must be closed if the same should be opened in a different mode. f cl ose( fileptr) ; Result Thus sequential and random disk I/O is executed using file handling functions. C Programming GE2155Computer Practice II cseannauniv.blogspot.in Vijai Anand SK 3.4.AWrite to a file character-by-character Program (chario.c) / * Fi l e I / O usi ng get c and put c f unct i ons */ #i ncl ude <st di o. h> #i ncl ude <st dl i b. h> mai n( ) { FI LE *f p; char c; f p=f open( " Char Fi l e. t xt ", "w") ; i f ( f p == NULL) { pr i nt f ( "Fi l e not Accessi bl e") ; exi t ( - 1) ; } / * Fi l e Wr i t e */ pr i nt f ( "I nput Text - - Ct r l + D t o Ter mi nat e\ n") ; / * Get dat a ( char by char ) f r omuser and wr i t e ont o f i l e*/ whi l e( ( c=get char ( ) ) ! = EOF) put c( c, f p) ; f cl ose( f p) ; } Output [ vi j ai @l ocal host f i l es] $ gcc chario.c [ vi j ai @l ocal host f i l es] $ ./a.out I nput Text - - Ct r l + D t o Ter mi nat e Wel come t o Fi l e handl i ng A f i l e shoul d be opened bef or e an I / O I / O shoul d not conf l i ct wi t h t he mode Af t er I / O f i l es shoul d be cl osed [ vi j ai @l ocal host f i l es] $ cat CharFile.txt Wel come t o Fi l e handl i ng A f i l e shoul d be opened bef or e an I / O I / O shoul d not conf l i ct wi t h t he mode Af t er I / O f i l es shoul d be cl osed C Programming GE2155Computer Practice II cseannauniv.blogspot.in Vijai Anand SK 3.4.BFile Statistics Program (filestat.c) / * St at i st i cs of f i l e- wor d, l i nes, char act er */ #i ncl ude <st di o. h> mai n( ) { FI LE *f p; char c; st at i c i nt l c, wc, cc; / * Fi l e Read and pr ocess */ f p=f open( " Char Fi l e. t xt ", "r ") ; whi l e( ( c=get c( f p) ) ! = EOF ) / * Pr ocess char - by- char */ { swi t ch( c) / * Count l i nes, wor ds and char act er */ { case ' \ n' : ++l c; ++wc; br eak; case ' ' : ++wc; br eak; def aul t : ++cc; } } pr i nt f ( "No. of l i nes : %d", l c) ; pr i nt f ( "\ nNo. of wor ds : %d", wc) ; pr i nt f ( "\ nNo. of char act er s ( spaces excl . ) : %d\ n", cc) ; f cl ose( f p) ; } Output [ vi j ai @l ocal host f i l es] $ gcc filestat.c [ vi j ai @l ocal host f i l es] $ ./a.out No. of l i nes : 4 No. of wor ds : 25 No. of char act er s ( spaces excl . ) : 109 C Programming GE2155Computer Practice II cseannauniv.blogspot.in Vijai Anand SK 3.4.CEmployee Record Program (emprec.c) / * Bi nar y I / O usi ng f wr i t e and r andomf r ead */ #i ncl ude <st di o. h> #i ncl ude <st r i ng. h> st r uct empl oyee { i nt code; char name[ 20] ; char desi g[ 20] ; f l oat basi c; }; mai n( ) { st r uct empl oyee casual , t emp; FI LE *f p; i nt i d, eno, n, pos, l b; i d = 1000; f p = f open( "Empl oyee. t xt " , "w") ; pr i nt f ( "\ t Ent er empl oyee det ai l s\ n" ) ; whi l e ( 1) { casual . code=i d++; pr i nt f ( "Empl oyee I d : %d" , casual . code) ; pr i nt f ( "\ nEnt er Name ( xxx t o qui t ) : ") ; scanf ( "%s" , casual . name) ; i f ( st r cmp( casual . name, "xxx") == 0) br eak; pr i nt f ( "Ent er Desi gnat i on : ") ; scanf ( "%s" , casual . desi g) ; pr i nt f ( "Ent er Basi c Sal ar y: ") ; scanf ( "%f " , &casual . basi c) ; f wr i t e ( &casual , si zeof ( casual ) , 1, f p) ; } n = f t el l ( f p) ; pr i nt f ( "\ nFi l e si ze : %d byt es\ n", n) ; f cl ose( f p) ; / * Recor d seek */ f p = f open( "Empl oyee. t xt " , "r ") ; pr i nt f ( "\ nEnt er Empl oyee i d : ") ; scanf ( "%d" , &eno) ; pos = ( eno- 1000) *si zeof ( casual ) ; C Programming GE2155Computer Practice II cseannauniv.blogspot.in Vijai Anand SK i f ( pos < n) { f seek( f p, pos, 0) ; f r ead ( &t emp, si zeof ( t emp) , 1, f p) ; pr i nt f ( "Empl oyee Name : %s\ n", t emp. name) ; pr i nt f ( "Empl oyee Desi gnat i on : %s\ n", t emp. desi g) ; pr i nt f ( "Empl oyee Basi c : %. 2f \ n", t emp. basi c) ; } el se pr i nt f ( "\ nI ncor r ect Empl oyee I d") ; f cl ose( f p) ; } Output Ent er empl oyee det ai l s Empl oyee I d : 1000 Ent er Name ( xxx t o qui t ) : Pr abakhar Ent er Desi gnat i on : Anal yst Ent er Basi c Sal ar y: 34000 Empl oyee I d : 1001 Ent er Name ( xxx t o qui t ) : Raghu Ent er Desi gnat i on : Admi ni st r at or Ent er Basi c Sal ar y: 28000 Empl oyee I d : 1002 Ent er Name ( xxx t o qui t ) : Gokul Ent er Desi gnat i on : Pr ogr ammer Ent er Basi c Sal ar y: 25000 Empl oyee I d : 1003 Ent er Name ( xxx t o qui t ) : Ramesh Ent er Desi gnat i on : Facul t y Ent er Basi c Sal ar y: 23000 Empl oyee I d : 1004 Ent er Name ( xxx t o qui t ) : Sur esh Ent er Desi gnat i on : At t ender Ent er Basi c Sal ar y: 5000 Empl oyee I d : 1005 Ent er Name ( xxx t o qui t ) : xxx Fi l e si ze : 240 byt es Ent er Empl oyee i d : 1003 Empl oyee Name : Ramesh Empl oyee Desi gnat i on : Facul t y Empl oyee Basi c : 23000. 00 C Programming GE2155Computer Practice II cseannauniv.blogspot.in Vijai Anand SK Ex. No: 3.5 Command Line Arguments Aim To study the use of command line arguments Command-line arguments are given after the name of a program in command-line operating systems like DOS or Linux, and are passed in to the program from the operating system. In C, main function can accept two arguments: one argument is number of command line arguments, and the other argument is a list of all of the command line arguments. mai n( i nt ar gc, char *ar gv[ ] ) The first one integer, (conventionally called argc) is the argument count. It is the number of arguments passed into the program from the command line, including the name of the program. The second is a pointer to an array of character strings (conventionally called argv), for argument vector that contains the arguments, one per string. argv[0] is the name of the program. After that, every element number less than argc is a command line argument. argv[argc] is a null pointer. C's model of command line arguments adheres to the following: Arguments are delimited by white space, which is either a space or a tab. A string surrounded by double quotation marks is interpreted as a single argument. A double quotation mark preceded by a backslash, \", is interpreted as". Two back slashe (\\) is replaced by a single backslash (\). For instance, the following command line is interpreted as $. / copy cnot es cpnot es argc =3 argv[0] =./copy argv[1] =cnotes argv[2] =cpnotes Command line arguments are typically used to pass the name of a data file to an application. Programs containing command line parameters are generally used to imitate OS commands. Result Thus arguments were passed to programs at command line and executed C Programming GE2155Computer Practice II cseannauniv.blogspot.in Vijai Anand SK 3.5.AListing command line arguments Program (cmdline.c) / * Command l i ne ar gument s */ #i ncl ude <st di o. h> mai n( i nt ar gc, i nt *ar gv[ ] ) { i nt i ; pr i nt f ( "Number of ar gument s : %d\ n" , ar gc) ; f or ( i =0; i <ar gc; i ++) pr i nt f ( "Ar gument [ %d] = %s\ n", i , ar gv[ i ] ) ; } Output [ vi j ai @l ocal host f i l es] $ gcc cmdline.c -o cmdline [ vi j ai @l ocal host f i l es] $ ./cmdline "C:\\Program Files\\Adobe" readme.txt Number of ar gument s : 3 Ar gument [ 0] = . / cmdl i ne Ar gument [ 1] = C: \ Pr ogr amFi l es\ Adobe Ar gument [ 2] = r eadme. t xt 3.5.BFile copy Program (filecopy.c) / * Fi l e copyi mi t at i ng cp command */ #i ncl ude <st di o. h> #i ncl ude <st dl i b. h> mai n( i nt ar gc, char *ar gv[ ] ) / * Command l i ne ar gument s */ { FI LE *sr c, *des; char ch; i f ( ar gc ! = 3) { pr i nt f ( "Ar gument s i nsuf f i ci ent \ n") ; pr i nt f ( "Usage : . / f i l ecopy sour ce dest \ n") ; exi t ( - 1) ; } sr c = f open( ar gv[ 1] , "r ") ; i f ( sr c==NULL ) { pr i nt f ( "Sour ce Fi l e not Acccessi bl e\ n") ; exi t ( - 1) ; } C Programming GE2155Computer Practice II cseannauniv.blogspot.in Vijai Anand SK des = f open( ar gv[ 2] , "w") ; i f ( des==NULL) { pr i nt f ( "Unabl e t o cr eat e Dest i nat i on f i l e\ n") ; exi t ( - 1) ; } whi l e ( 1) { ch=get c( sr c) ; i f ( ch==EOF) br eak; el se put c( ch, des) ; } pr i nt f ( "Fi l e Copi ed\ n") ; f cl ose( sr c) ; f cl ose( des) ; } Output [ vi j ai @l ocal host f i l es] $ gcc filecopy.c -o filecopy [ vi j ai @l ocal host f i l es] $ . / f i l ecopy Random. t xt Ar gument s i nsuf f i ci ent Usage : . / f i l ecopy sour ce dest [ vi j ai @l ocal host f i l es] $ ./filecopy Random.txt r.txt Fi l e Copi ed [ vi j ai @l ocal host f i l es] $ l s a. out char i o. c cmdl i ne. c empr ec. c f i l ecopy. c r andom. c r . t xt Char Fi l e. t xt cmdl i ne Empl oyee. t xt f i l ecopy f i l est at . c Random. t xt [ vi j ai @l ocal host f i l es] $ cmp Random. t xt r . t xt [ vi j ai @l ocal host f i l es] $ 3.5.CDisplay file contents Program (filecat.c) / * Cat command */ #i ncl ude <st di o. h> mai n( i nt ar gc, char *ar gv[ ] ) { FI LE *f p; char c; i f ( ar gc ! = 2) { f pr i nt f ( st der r , "I nsuf f i ci ent ar gument s\ n") ; f pr i nt f ( st der r , "Usage: . / f i l ecat f i l ename\ n" ) ; exi t ( - 1) ; } C Programming GE2155Computer Practice II cseannauniv.blogspot.in Vijai Anand SK f p = f open( ar gv[ 1] , "r ") ; i f ( f p == NULL) { f pr i nt f ( st der r , "cat : can' t open %s\ n", ar gv[ 1] ) ; exi t ( - 1) ; } whi l e( ( c = get c( f p) ) ! = EOF) put char ( c) ; f cl ose( f p) ; } Output [ vi j ai @l ocal host f i l es] $ gcc filecat.c -o filecat [ vi j ai @l ocal host f i l es] $ . / f i l ecat I nsuf f i ci ent ar gument s Usage: . / f i l ecat f i l ename [ vi j ai @l ocal host f i l es] $ . / f i l ecat char f i l e. t xt cat : can' t open char f i l e. t xt [ vi j ai @l ocal host f i l es] $ ./filecat CharFile.txt Wel come t o Fi l e handl i ng A f i l e shoul d be opened bef or e an I / O I / O shoul d not conf l i ct wi t h t he mode Af t er I / O f i l es shoul d be cl osed