Presentation is loading. Please wait.

Presentation is loading. Please wait.

Unit II : Pointers in C and file handling Objective : 1.To understand the basic operations with pointers. 2.To make the student understand the concept.

Similar presentations


Presentation on theme: "Unit II : Pointers in C and file handling Objective : 1.To understand the basic operations with pointers. 2.To make the student understand the concept."— Presentation transcript:

1

2 Unit II : Pointers in C and file handling Objective : 1.To understand the basic operations with pointers. 2.To make the student understand the concept of static and dynamic memory allocation and conservation of memory for the programs. 3.To make the student know how to access the underlining hardware and also to understand the disadvantage of it. 4.To introduce the student to access and manipulate data stored in disk file. Contents : Pointer, pointer to pointer,pointer to single and multidimensional arrays, array of pointers, string and structure manipulation using pointers, pointer to functions. Pointer to file structure and basic operations on file, functions used for text and binary file handling in C.

3 Teaching Plan for Unit2 Pointer Variable Declarations and Initialization Relationship Between Pointers and Arrays String Pointers Arrays of Pointers Pointer to an array Pointer to Pointer Function returning Pointer Pointer to Function Dynamic memory allocation for 1 D array Pointer to structure File Handling Command Line arguments University Solved Question Paper

4 Pointer declarations – * used with pointer variables int *myPtr; – Declares a pointer to an int (pointer of type int * ) – Multiple pointers require using a * before each variable declaration int *myPtr1, *myPtr2; – Can declare pointers to any data type – Initialize pointers to 0, NULL, or an address 0 or NULL – points to nothing ( NULL preferred) Pointer Variable Declarations and Initialization

5 & (address operator) – Returns address of operand int y = 5; int *yPtr; yPtr = &y; // yPtr gets address of y yPtr “points to” y yPtr y 5 yptr 500000600000 y 5 Address of y is value of yptr

6 Array Example Using a Pointer int x[4] = {12, 20, 39, 43}, *y; y = &x[0];// y points to the beginning of the array printf("%d\n", x[0]);// outputs 12 printf("%d\n", *y);// also outputs 12 printf("%d\n", *y+1);// outputs 13 (12 + 1) printf("%d\n", (*y)+1);// also outputs 13 printf("%d\n", *(y+1));// outputs x[1] or 20 y+=2;// y now points to x[2] printf("%d\n", *y);// prints out 39 *y = 38;// changes x[2] to 38 printf("%d\n", *y-1);// prints out x[2] - 1 or 37 *y++;// sets y to point at the next array element printf("%d\n", *y);// outputs x[3] (43) (*y)++;// sets what y points to to be 1 greater printf("%d\n", *y);// outputs the new value of x[3] (44)

7 Relationship Between Pointers and Arrays Arrays and pointers closely related – Array name like constant pointer – Pointers can do array subscripting operations Accessing array elements with pointers – Element b[ n ] can be accessed by *( bPtr + n ) Called pointer/offset notation – Addresses &b[ 3 ] same as bPtr + 3 – Array name can be treated as pointer b[ 3 ] same as *( b + 3 ) – Pointers can be subscripted (pointer/subscript notation) bPtr[ 3 ] same as b[ 3 ]

8 1 // 20.cpp 2 // Using subscripting and pointer notations with arrays. 3 4 #include 5 6 using std::cout; 7 using std::endl; 8 9 int main() 10 { 11 int b[] = { 10, 20, 30, 40 }; 12 int *bPtr = b; // set bPtr to point to array b 13 14 // output array b using array subscript notation 15 cout << "Array b printed with:\n" 16 << "Array subscript notation\n"; 17 18 for ( int i = 0; i < 4; i++ ) 19 cout << "b[" << i << "] = " << b[ i ] << '\n';

9 21 // output array b using the array name and 22 // pointer/offset notation 23 cout << "\nPointer/offset notation where " 24 << "the pointer is the array name\n"; 25 26 for ( int offset1 = 0; offset1 < 4; offset1++ ) 27 cout << "*(b + " << offset1 << ") = " 28 << *( b + offset1 ) << '\n'; 29 30 // output array b using bPtr and array subscript notation 31 cout << "\nPointer subscript notation\n"; 32 33 for ( int j = 0; j < 4; j++ ) 34 cout << "bPtr[" << j << "] = " << bPtr[ j ] << '\n'; 35 36 cout << "\nPointer/offset notation\n"; 37

10 38 // output array b using bPtr and pointer/offset notation 39 for ( int offset2 = 0; offset2 < 4; offset2++ ) 40 cout << "*(bPtr + " << offset2 << ") = " 41 << *( bPtr + offset2 ) << '\n'; 42 43 return 0; // indicates successful termination 44 // All Notations used -> b[ i ],*( b + i ),* ( i +b), i [ b ] 45 } // end main Array b printed with: Array subscript notation b[0] = 10 b[1] = 20 b[2] = 30 b[3] = 40

11 Pointer/offset notation where the pointer is the array name *(b + 0) = 10 *(b + 1) = 20 *(b + 2) = 30 *(b + 3) = 40 Pointer subscript notation bPtr[0] = 10 bPtr[1] = 20 bPtr[2] = 30 bPtr[3] = 40 Pointer/offset notation *(bPtr + 0) = 10 *(bPtr + 1) = 20 *(bPtr + 2) = 30 *(bPtr + 3) = 40

12 1D String Array and Pointers Example main() { char name[]=“scoe”; int i; while(name[i]) { printf(“\n %c %c %c %c”, name[i], *(name+i), *(i+name), i[name]); i++; } Output: ssss cccc oooo eeee

13 int strlen(char *s) { int n; for(n = 0; *s != ‘\0’; s++) n++; return n; } int strcmp(char *s, char *t) { int i; for(i=0;s[i] = = t[i];i++) if(s[i] = = ‘\0’) return 0; return s[i] – t[i]; } int strcmp(char *s, char *t) { for( ; *s = = *t; s++, t++) if(*s = = ‘\0’) return 0; return *s - *t; } Implementing String Operations

14 void strcpy(char *s, char *t) { while((*s = *t) != ‘\0’) { s++; t++; } void strcpy(char *s, char *t) { while((*s++ = *t++) != ‘\0’); } void strcpy(char *s, char *t) { int i = 0; while((s[i] = t[i]) != ‘\0’) i++; } void strcpy(char *s, char *t) { int i; while( *(*t+i)!=‘\0’) { *(s+i)= *( t+i); s++ ;t++; i++; } *( s + i )= ‘\0’; } Implementing String Operations (Contd..)

15 Arrays of Pointers Arrays can contain pointers For example: an array of strings char *suit[ 4 ] = { "Hearts", "Diamonds", "Clubs", "Spades" }; – Strings are pointers to the first character – char * – each element of suit is a pointer to a char – The strings are not actually stored in the array suit, only pointers to the strings are stored – suit array has a fixed size, but strings can be of any size suit[3] suit[2] suit[1] suit[0]’H’’e’’a’’r’’t’’s’ ’\0’ ’D’’i’’a’’m’’o’’n’’d’’s’ ’\0’ ’C’’l’’u’’b’’s’ ’\0’ ’S’’p’’a’’d’’e’’s’ ’\0’

16 int i; char *college[]= {“scoe",”skn",”nbn"}; for (i= 0; i < 3; i++} { printf ("String %d is %s\n",i+1,college[i]); } String 1 is scoe String 2 is skn String 3 is nbn Will print: Arrays of Pointers ( contd..)

17 Arrays of Pointer char *x[ ] = {"hello", "goodbye", "so long", "thanks for all the fish"}; // our array of strings x is a set of 4 pointers char *y;// let y be a pointer to a char so it can be used to move through a single string int i; for(i=0;i<4;i++)// iterate for each string in x { y = x[i];// x[i] is an array, x is really a pointer, so this sets y to x’s starting addr. while(*y!='\0') // while the thing y points to is not the end of a string { printf("%c", *y);// print what y points to y++;// and go on to the next char in x } printf("\n");// separate strings in output with \n }

18 Pointer to an array main() { int a[][4]={5,7,5,9,4,6,3,1,2,9,0,6}; int *p; int (*q)[4]; p=(int*)a; q=a; printf(:\n %u %u”,p,q); p++; q++; printf(“\n %u %u”,p,q); } Output : 65500 65500 65502 65508

19 Pointers to Pointers A pointer can also be made to point to a pointer variable (but the pointer must be of a type that allows it to point to a pointer) Example: int V = 101; int *P = &V;/* P points to int V */ int **Q = &P;/* Q points to int pointer P */ printf(“%d %d %d\n”,V,*P,**Q); /* prints 101 3 times */

20 Pointers to Pointers(Contd..) char **marker; char course[0]=“numerical “,course[1]=“methods”; marker=&course[0]; //pointer to course[0] which points to numerical marker ++; //points to course[1] which points to methods (*marker)++; //will point to ‘e’

21 Function Returning Pointers float *findMax(float A[], int N) { int I; float *theMax = &(A[0]); for (I = 1; I < N; I++) if (A[I] > *theMax) theMax = &(A[I]); return theMax; } void main() { float A[5] = {0.0, 3.0, 1.5, 2.0, 4.1}; float *maxA; maxA = findMax(A,5); *maxA = *maxA + 1.0; printf("%.1f %.1f\n",*maxA,A[4]); }

22 /* function to generate and return random numbers. */ int * getRandom( ) { static int r[10]; int i; /* set the seed */ srand( (unsigned)time( NULL ) ); for ( i = 0; i < 10; ++i) { r[i] = rand(); printf("%d\n", r[i] ); } return r; } /* main function to call above defined function */ int main () { /* a pointer to an int */ int *p; int i; p = getRandom(); for ( i = 0; i < 10; i++ ) { printf("*(p + [%d]) : %d\n", i, *(p + i) ); } return 0; } Function Returning Pointers (Contd..)

23 main() { int *p; int *fun(); p=fun(); printf(“\n %u”,p); printf(“\n %d”,*p); } int *fun() { int i=20; return (&i); } Output :Garbage value Declare static int i=20 in fun() Function Returning Pointers (Contd..)

24 Declarations Examples int * E [5] E is a 1D array of size 5 of pointers to ints int (* F) [5] F is a pointer to a 1D array of size 5 of ints char * H (…) H is a function returning a pointer to a char int *p(char *a) p is function that accept pointer to cahr argument & return pointer to integer int (*p)(char *a) p is pointer to a function that accept pointer to char argument & return an integer quantity Int (*p)(char (*a)[]) p is pointer to a function that accept pointer to char array as a argument & return an integer quantity int *(*p) (char *a[]) p is pointer to a function that accept array of char as a argument & return a pointer to an integer

25 Pointers to Functions Example: bubblesort – Function bubble takes a function pointer bubble calls this helper function this determines ascending or descending sorting – The argument in bubblesort for the function pointer: int ( *compare )( int a, int b ) tells bubblesort to expect a pointer to a function that takes two ints and returns an int – If the parentheses were left out: int *compare( int a, int b ) Defines a function that receives two integers and returns a pointer to a int

26 Notice the function pointer parameter.

27

28 ascending and descending return true or false. bubble calls swap if the function call returns true. Notice how function pointers are called using the dereferencing operator. The * is not required, but emphasizes that compare is a function pointer and not a function.

29

30

31 int func (int a, int b) { printf("\n a = %d\n",a); printf("\n b = %d\n",b); return 0; } int main(void) { int(*fptr)(int,int); // Function pointer fptr = func; // Assign address to function pointer func(2,3); fptr(2,3); return 0; } Output: a = 2 b = 3 a = 2 b = 3 Pointers to Functions

32 Passing Arrays Arrays are passed “by reference”. When an array is passed to a function, the address of the array is copied onto the function parameter. Since an array address is a pointer, the function parameter may be declared in either fashion. E. g. int sumArray( int a[ ], int size) is equivalent to int sumArray( int *a, int size) The code in the function is free to use “ a ” as an array name or as a pointer as it sees fit. The compiler always sees “ a ” as a pointer. In fact, any error messages produced will refer to “ a ” as an int *

33 int sumArray( int a[ ], int size) { int k, sum = 0; for (k = 0; k < size; k++) sum += a[ k ]; return sum; } int sumArray( int a[ ], int size) { int k, sum = 0; for (k = 0; k < size; k++) sum += *(a + k); return sum; } int sumArray( int a[ ], int size) { int k, sum = 0; for (k = 0; k < size; k++) } sum += *a; ++a; } return sum; } sumArray

34 malloc Prototype: int malloc(int size); – function searches heap for size contiguous free bytes – function returns the address of the first byte – programmers responsibility to not lose the pointer – programmers responsibility to not write into area past the last byte allocated Example: 012345678910111213141516 Key new allocation char *ptr; ptr = malloc(4); // new allocation ptr 10

35 free Prototype: int free(int ptr); –releases the area pointed to by ptr –ptr must not be null trying to free the same area twice will generate an error Example: initial memory 01234567 Key free memory free(ptr); p1 5 after free p2 2 2 p1 null

36 sizeof() Function The sizeof() function is used to determine the size of any data type – prototype: int sizeof(data type); – returns how many bytes the data type needs for example: sizeof(int) = 4, sizeof(char) = 1 – works for standard data types and user defined data types (structures)

37 Dynamic Memory allocation for 1D Array main() { int n, avg,*p, sum=0; printf(“\n Enter the number of Students :”); scanf(“%d”,&n); p=(int*)malloc(n*2); if(p==NULL) { printf(“\n Memory allocation unsuccessful); exit(0); } for(i=0;i<n;i++) scanf(“%d”,(p+i); for(i=0; i<n;i++) sum=sum+ *(p+i); avg=sum/n; printf(“\n Average Marks %d”, avg); free(p); } main() { int l; char s[10]; char *p; printf(“\n Enter Strings :”); gets(s); l=strlen(s); p=(char*)malloc(sizeof(l+1)); for(i=0; *(s+i)!=‘\0’;i++) * (p + i) =*( s + i ); *(p+i)=‘\0’; printf(Copied String : %s”,s); free(p); }

38 Passing 2D array to function main() { int a[3][4]= {1,2,3,4,5,6,7,8,9,10,11,12}; display(a,3,4); show(a,3,4); info(a,3,4); } void display( int *q, int row, int col) { int i, j; for(i=0;i<row;i++) for(j=0;j<col;j++) printf(“ %d”,*(q+i*col+j); } void show(int *q[4],int row,int col) { int i,j, *p; for(i=0;i<row;i++) { p=q+i; for(j=0;j<col;j++) printf(“ %d”, *(p+j); } void info( int *q[4], int row, int col) { int i, j; for(i=0;i<row;i++) for(j=0;j<col;j++) printf(“ %d”,*(*(q+ i)+j)); }

39 Dynamic memory allocation for 2D-Array main() { int col,row,nrows,ncols; int *a[20]; printf(“\n Enter Rows”); scanf(“%d”,&nrows); printf(“\n Enter Cols”); scanf(“%d”,&ncols); for(row=0;row<nrows;row++) //Memory allocation { a[row]=(int*)malloc(ncols*sizeof(int)); } printf(“\n Enter Matrix:”); for(row=0;row<nrows;row++) { for(col=0;col<ncols;col++) scanf(“%d”,(*(a+row)+col); //scanf(“%d”,a[row][col]); }

40 main() { int **a; //pointer to pointer int r,c; printf(“\n Eneter row and col :”); scanf(“%d%d”,&r,&c); *a=(int*)malloc(sizeof(int)*r); for(i=0;i<r;i++) a[i]=(int*)malloc (sizeof(int)*c); for(i=0;i<r;i++) for(j=0;j<c;j++) scanf(“%d”,(*(a+i)+j); } Dynamic memory allocation for 2D-Array

41 Assume a 2-D array of characters is needed – this is basically an array of strings Assume 4 strings with a max of 80 chars int main() { char** names; int i; names = (char**)malloc(4 * sizeof(char*)); for(i=0; i<4; i++) names[i] = (char*)malloc(80 * sizeof(char)); for(i=0; i<4; i++) free(names[i]); free(names); return 0; } Dynamic memory allocation for 2D-Array

42 Dynamically Allocating 2D Array using calloc() float **A; /* A is an array (pointer) of float pointers */ int I; A = (float **) calloc(5,sizeof(float *)); /* A is a 1D array (size 5) of float pointers */ for (I = 0; I < 5; I++) A[I] = (float *) calloc(4,sizeof(float)); /* Each element of array points to an array of 4 float variables */ /* A[I][J] is the Jth entry in the array that the Ith member of A points to */

43 Realloc Realloc it is for times when you've used malloc to get the size of array but need it bigger again (or perhaps smaller). Realloc allows you to say "the memory I grabbed before was the wrong size - I need to change the size but keep the first bit the same). You will probably not use realloc much. In any case realloc is inefficient.

44 realloc Example float *nums; int I; nums = (float *) calloc(5, sizeof(float)); /* nums is an array of 5 floating point values */ for (I = 0; I < 5; I++) nums[I] = 2.0 * I; /* nums[0]=0.0, nums[1]=2.0, nums[2]=4.0, etc. */ nums = (float *) realloc(nums,10 * sizeof(float)); /* An array of 10 floating point values is allocated, the first 5 floats from the old nums are copied as the first 5 floats of the new nums, then the old nums is released */

45 Pointers to Structs #include struct foo {// a global definition, the struct foo is known in all of int a, b, c;// these functions }; // function prototypes void inp(struct foo *);// both functions receive a pointer to a struct foo void outp(struct foo); void main( ) { struct foo x;// declare x to be a foo inp(&x);// get its input, passing a pointer to foo outp(x);// send x to outp, this requires 2 copying actions } void inp(struct foo *x) {// notice the notation here: &ptr->member scanf("%d%d%d", &x->a, &x->b, &x->c); } void outp(struct foo x)// same notation, but without the & { printf("%d %d %d\n", x.a, x.b, x.c); }

46 Nested structs through pointers Now consider the following struct rectangle r, *rp; rp = &r; Then the following are all equivalent r.pt1.x rp->pt1.x (r.pt1).x (rp->pt1).x But not rp->pt1->x (since pt1 is not a pointer to a point) struct point { int x; int y; } struct rectangle { struct point pt1; struct point pt2; } If we have struct rectangle r; Then we can reference r.pt1.x, r.pt1.y, r.pt2.x and r.pt2.y

47 Accessing Structure array using Pointers typedef struct Student { int RollNo; char Name[20]; } S; void main() { S Student[3],*p; int i,n=3; for(i=0;i<3;i++) scanf(“%d%s”,&s[i].Rollno,s[i].Name); p=&s[0]; for(i=0;i<3;i++) { printf(“\n Rollno %d Name %s”,p->RollNo,p->Name); p++; }

48 Dynamic Memory allocation for Structure typedef struct Student { int RollNo; char Name[20]; } S; void main() { S *p; int i,n; printf("\n Enter total no. of Records :"); scanf("%d",&n); p=(S*)malloc(sizeof(S)*n); for(i=0;i<n;i++) { printf("\n Enter the RollNo & Name :"); scanf("%d",&(p->RollNo)); flushall(); gets(p->Name); p++; //go to next record } for(i=0;i<n;i++) { printf("\nRollNo %d",p->RollNo); printf("\nName %s",p->Name); p++; }

49 What is a File? A file is a collection of related data that a computers treats as a single unit. Computers store files to secondary storage so that the contents of files remain intact when a computer shuts down. When a computer reads a file, it copies the file from the storage device to memory; when it writes to a file, it transfers data from memory to the storage device. FILE stdio.h C uses a structure called FILE (defined in stdio.h ) to store the attributes of a file.

50 Steps in Processing a File FILE FILE *p; 1. Create the stream via a pointer variable using the FILE structure: FILE *p; 2. Open the file, associating the stream name with the file name. 3. Read or write the data. 4. Close the file.

51 The basic file operations are fopen - open a file- specify how its opened (read/write) and type (binary/text) fclose - close an opened file fread - read from a file fwrite - write to a file fseek/fsetpos - move a file pointer to somewhere in a file. ftell/fgetpos - tell you where the file pointer is located.

52 File Open Modes

53 More on File Open Modes

54 Additionally, r+ - open for reading and writing, start at beginning w+ - open for reading and writing (overwrite file) a+ - open for reading and writing (append if file exists)

55 File Open fopen The file open function ( fopen ) serves two purposes: – It makes the connection between the physical file and the stream. – It creates “a program file structure to store the information” C needs to process the file. filepointer= fopen(“filename”, “mode”); Syntax: filepointer= fopen(“filename”, “mode”);

56 More On fopen The file mode tells C how the program will use the file. The filename indicates the system name and location for the file. fopen We assign the return value of fopen to our pointer variable: spData = fopen(“MYFILE.TXT”, “w”); spData = fopen(“A:\\MYFILE.TXT”, “w”);

57 More On fopen from Figure 7-3 in Forouzan & Gilberg, p. 399

58 Closing a File When we finish with a mode, we need to close the file before ending the program or beginning another mode with that same file. fclose fclose(spData); To close a file, we use fclose and the pointer variable: fclose(spData);

59 fprintf() Syntax: fprintf (fp,"string",variables);Example: int i = 12; float x = 2.356; char ch = 's'; FILE *fp; fp=fopen(“out.txt”,”w”); fprintf (fp, "%d %f %c", i, x, ch);

60 fscanf() Syntax: fscanf (fp,"string",identifiers);Example: FILE *fp; Fp=fopen(“input.txt”,”r”); int i; fscanf (fp,“%d",i);

61 getc() Syntax: identifier = getc (file pointer);Example: FILE *fp; fp=fopen(“input.txt”,”r”); char ch; ch = getc (fp);

62 putc() write a single character to the output file, pointed to by fp.Example: FILE *fp; char ch; putc (ch,fp);

63 End of File fscanf There are a number of ways to test for the end-of-file condition. Another way is to use the value returned by the fscanf function: FILE *fptr1; int istatus ; istatus = fscanf (fptr1, "%d", &var) ; if ( istatus == feof(fptr1) ) { printf ("End-of-file encountered.\n”) ; }

64 Reading and Writing Files #include int main ( ) { FILE *outfile, *infile ; int b = 5, f ; float a = 13.72, c = 6.68, e, g ; outfile = fopen ("testdata", "w") ; fprintf (outfile, “ %f %d %f ", a, b, c) ; fclose (outfile) ; infile = fopen ("testdata", "r") ; fscanf (infile,"%f %d %f", &e, &f, &g) ; printf (“ %f %d %f \n ", a, b, c) ; printf (“ %f %d %f \n ", e, f, g) ; }

65 Example #include void main() { char ch; FILE *fp; fp=fopen("out.txt","r"); while(!feof(fp)) { ch=getc(fp); printf("\n%c",ch); } getch(); }

66 fread () Declaration: size_t fread(void *ptr, size_t size, size_t n, FILE *stream); Remarks: fread reads a specified number of equal-sized data items from an input stream into a block. ptr = Points to a block into which data is read size = Length of each item read, in bytes n = Number of items read stream = file pointer

67 Example Example: #include int main() { FILE *f; char buffer[11]; if (f = fopen("fred.txt", “r”)) { fread(buffer, 1, 10, f); buffer[10] = 0; fclose(f); printf("first 10 characters of the file:\n%s\n", buffer); } return 0; }

68 Read Student File

69 Reading a Structure

70 fwrite() Declaration: size_t fwrite(const void *ptr, size_t size, size_t n, FILE*stream); Remarks: fwrite appends a specified number of equal-sized data items to an output file. ptr = Pointer to any object; the data written begins at ptr size = Length of each item of data size = Length of each item of data n =Number of data items to be appended n =Number of data items to be appended stream = file pointer stream = file pointer

71 Example Example: #include int main() { char a[10]={'1','2','3','4','5','6','7','8','9','a'}; FILE *fs; fs=fopen("Project.txt","w"); fwrite(a,1,10,fs); fclose(fs); return 0; }

72 fseek() This function sets the file position indicator for the stream pointed to by stream or you can say it seeks a specified place within a file and modify it. SEEK_SET Seeks from beginning of file SEEK_CUR Seeks from current position SEEK_CUR Seeks from current position SEEK_END Seeks from end of file SEEK_END Seeks from end of fileExample: #include int main() { FILE * f; f = fopen("myfile.txt", "w"); fputs("Hello World", f); fseek(f, 6, SEEK_SET); SEEK_CUR, SEEK_END fputs(" India", f); fclose(f); return 0; }

73

74 ftell() offset = ftell( file pointer ); "ftell" returns the current position for input or output on the file #include int main(void) { FILE *stream; stream = fopen("MYFILE.TXT", "w"); fprintf(stream, "This is a test"); printf("The file pointer is at byte %ld\n", ftell(stream)); fclose(stream); return 0; }

75 Current Location (ftell) Operation

76 FIGURE 13-11 Rewind File

77 Command-Line Arguments The main function may have parameters named argc and argv, which allow access to the command line when the program is executed: int main(int argc, char *argv[]) { … } argc is a count of the number of command line arguments (including the name of the program itself). argv is an array of pointers to the command line arguments. argv[0] contains a pointer to the name of the program. argv[1] through argv[argc-1] point to the remaining command line arguments.

78 1. Initialize variables 2. Function calls ( fopen ) 2.1 Specify open type (read or write) 3. Copy file 1/* Fig. 14.3: fig14_03.c 2 Using command-line arguments */ 3#include 4 5int main( int argc, char *argv[] ) 6{6{ 7 FILE *inFilePtr, *outFilePtr; 8 int c; 9 10 if ( argc != 3 ) 11 printf( "Usage: copy infile outfile\n" ); 12 else 13 if ( ( inFilePtr = fopen( argv[ 1 ], "r" ) ) != NULL ) 14 15 if ( ( outFilePtr = fopen( argv[ 2 ], "w" ) ) != NULL ) 16 17 while ( ( c = fgetc( inFilePtr ) ) != EOF ) 18 fputc( c, outFilePtr ); 19 20 else 21 printf( "File \"%s\" could not be opened\n", argv[ 2 ] ); 22 23 else 24 printf( "File \"%s\" could not be opened\n", argv[ 1 ] ); 25 26 return 0; 27} Notice argc and argv[] in main argv[1] is the second argument, and is being read. argv[2] is the third argument, and is being written to. Loop until End Of File. fgetc a character from inFilePtr and fputc it into outFilePtr.

79 Example args.c $ cc args.c -o args.out $./args.out 2 join leave 6 6 leave join 2./args.out $ #include main(int argc,char *argv[]) { while(argc>0) /* print out all arguments in reverse order*/ { printf("%s\n",argv[argc-1]); argc--; }

80 Text File Vs Binary File Handling of newlines Representation of end of file Storage of numbers

81 Sr No Paper NumberTotal Marks Type of Question 12962-19224Theory Questions 23062-1923212M - Give output of the Program 20 M- Theory Questions 33162-1923420M - Give output of the Program 14 M-Theory Questions 43262-192175M- Give Output of the Program 12M – Theory Questions 53762-232 (2009-10 Sem-II) 24Give output of the Program 74062-212 (2011-12 Sem-I) 18Theory Questions 84162-212 (2011-12 Sem-II) 10Theory Questions 94262-212 (2012-13 Sem-I) 159M - Give Output of the Program 12M – Theory Questions Analysis of mark Distribution for Unit2

82 int array[]{45,67,89}; int *array_ptr=array; printf(“\nFirst Element= %d”,*(array_ptr++)); printf(“\nSecond Element= %d”,*(array_ptr++)); printf(“\nThird Element= %d”,*array_ptr); Output: First Element=45 Second Element=67 Second Element=67 Third Element=89 Third Element=89 int i,j[2]={0},*p,*q; p=&i;*p=3;*++(q)=1; printf(“ %d %d %d”,i,j[0],j[1]); Output :3 0 1 University Questions

83 void f1(int *px) { int n=100; px = &n; } int main() { int *x; f1(x); printf(“%d”,x); } Output : Any Garbage Value int t[3][2[4]={2,4,3,6,1,6,7,9,8,2,1,1,2,3,7,3,1,6,2,4,0,7,9,5}; printf(“ %d”,*(*(*(t+2)+1)+3)); Output :3 char *cp; int *ip; cp=(char *)0X100; ip=(int*)cp; ip++; cp++; printf(cp= %x ip= %x”,cp.ip); Output : 101 102. University Questions

84 int x=10,y=10; Int *p1=&x,*p2=&y, z; printf(“%d”,*(p1)++); - 10 printf(“%d”,--(*p2); - 9 printf(“%d”, *p1+(*p2)--;); - 20 printf(“ %d “,++(*p2)-*p1); - 2 printf(“ %d”*p1+*p2); - 20 printf(“ %d”, --*(p1) +*(p2)); - 19 printf(“%d”,*p1++); -10 *p2+=*p2++ + ++*p2; printf(“ %d”,*p2); -10 int a[4][3]={{2,4,3},{6,8,5},{3,5,1}}; printf( “ %d %d %d”,*n,n[2][2],n[3][2]); Error : undefined symbol n,Warning value of ‘A’ never used University Questions

85 Explain the following declarations :- int *P[5]; ->Array of Pointers int **q; -> Pointer to pointer float(*p)(int no); ->Pointer to the function int(*q)[3] -> q is a pointer to array of size 3 of int Int*fun1(int *x) ->fun1 return the pointer value and passit by reference University Questions

86 char *a =NULL; scanf(“%s”,a);printf(“%s”,a); Output :NULL int a[2][3] ={1,3,5,0,7}; printf(“%d”,*(*a+0)+2)); Output :3 char string[10]= “abcd”; printf(“%d”,*(string+3)); Output:100 (ASCII value of d) int a=15,*b=&a,**c=&b; printf(“ %d”,**(&b)); Output :15 University Questions

87 char *x=“1234”; char *y; y=x; printf(“%s”,y); Output :1234 int arr[]={1,2,3,4}; int *ptr =arr; *(arr+3) = * ++ptr + *ptr++; printf(“ %d %d %d”,*(arr+0),*(arr+1),*(arr+2),*(arr+3)); Output : 1 2 3 4 University Questions Paper Number : 2668-152

88 int main(void) { void f(char *); f(“abcd”); return (0); } void f(char *p) { if(*p) { f(p+1); } printf(“%c”,*p); } Output:dcba void main(void) { char *p=“bye”; void f(char *); f(p); printf(“%s”,p); } void f(char *p) { p=(char *)malloc(6); strcpy(p,”hello”); } Output:bye University Questions Paper Number : 2668-152

89 Thank You!!


Download ppt "Unit II : Pointers in C and file handling Objective : 1.To understand the basic operations with pointers. 2.To make the student understand the concept."

Similar presentations


Ads by Google