Вы находитесь на странице: 1из 10

Programming in C

Chapter-11,12

Pointers
Introduction
A pointer is can contain memory as their values. Memory locations are nothing but the place where programs data have been stored. So pointer can be used to access the data stored in the memory.

Memory Layout
Computers memory is a sequential collection of storage cells known as bytes. Each byte(address) are given unique address. First byte will be given address 0, second byte will be given address as 1, third byte will be given address 2 and so on. So the address of nth byte would be n-1. Memory layout of 64K = 65536 bytes. Memory Cell Address 0 1 2 3 4 5 . . . . . . 65535 As first bytes address is 0 last bytes (i.e. 65536 th byte) address is 65535 So when we declare a variable at that time system allocates memory location to variable(s) from the available free bytes in the memory. For example if we declare int no =500; then the system will allocate 2 bytes(as int occupies 2 bytes) to no and will store the value 500 at that place. So how it would look like: no 500 6700 variable name variables value variables address
1 D. D. University Nadiad

Prof. Chirag I Patel BCA Dept.

Programming in C

Chapter-11,12

So in memory at location 6700 and 6701 the value 500 will be stored for the variable no.

Underlying concepts of pointer


Pointer constants: Memory addresses are known as pointer constants. Pointer values: Address of variable is known as pointer values. Address of any variable can be accesses by &. Pointer variable or pointer: A variable which can store pointer is known as pointer variable or pointer Or Pointer is a variable which can store the address of another variable.

Accessing address of a variable


We can access address of any variable by using & operator. For example: int no=20; Now to get the address of no we need to write: &no To print the address we can write following line: printf(%u,&no); As address is unsigned integer we should use %u to print address, otherwise system may print incorrect value of address on the screen.

Declaring pointer variable


A pointer can be declared as the following syntax: datatype * ptr_name; Where datatype can be inbuilt like int,float etc. or user defined like struct, union etc. * Means pointer ptr_name is a variable name. For example: int *ptr; Meaning of above line is that ptr is a pointer and can store address of integer variable only in it. That is ptr is the pointer to the integer. But ptr is not an integer. Another example char *ptr;

Prof. Chirag I Patel BCA Dept.

D. D. University Nadiad

Programming in C

Chapter-11,12

Meaning of above line is that ptr is a pointer and can store address of char variable only in it. That is ptr is the pointer to the character. But ptr is not a character. So in both examples we have seen that ptr stores address of particular data type and we known that address is unsigned integer and unsigned integer occupies 2 bytes in the memory so generally any pointer occupies 2 bytes.

Pointer initialization
A pointer can be initialized by assignment operator. For example int no=30; int *ptr;/*pointer declaration pointer to integer*/ ptr=&no; /*pointer initialization address of no is stored in ptr*/ We can also combine line2 and 3 as follows: int *ptr=&no; /*declaration and initialization together*/ We must make sure that pointer stores address of related type of data. That is pointer to int can store address of integer only, pointer to float can store address of float only and so on. For example: char ch= A; int no=40; int *ptr=&ch; /* not correct */ Here in last line we are trying store address of character in ptr but ptr can store address of integer so it is not correct and system may give wrong output. It is possible to declare variable, pointer variable initialization of pointer variable in one line. For example: int no, *ptr=&no; is perfectly valid. But following is not correct: int *ptr=&no, no; As we are declaring pointer first and no afterwards, it is an error. We can initialize a pointer with any of the following three values only: 1. Zero 2. NULL 3. Address of any variable. For example: int *ptr=0; or int *ptr=NULL or int no, *ptr=&no;
Prof. Chirag I Patel BCA Dept. 3 D. D. University Nadiad

and

Programming in C

Chapter-11,12

are valid examples. But int *ptr=9000; is not valid. That means we cannot assign absolute address to the pointer variable.

Changing value of variable by pointer


We can access or change the value of variable by using pointer by using * operator. So when we write * before the variable address we can get value stored at that address. For example: int no=30, *ptr; ptr=&no; *ptr=40; printf(%d,no); /*line1*/ /*line2*/ /*line3 same as *&no =40 or no=40 */ /*line4*/

It will print value 40 as we have changed value of no by using ptr. Let us look graphically how it happened:
After line1 After line2 After line3

no
30 6234

ptr
garbage 8700

no
30

ptr
6234

no
30 40 6234

ptr
6234 8700

8700 6234 So now ptr points to 30 in memory, so 30 can be accessed by no as well as ptr

So if we write ptr we will get 6234 and if we write *ptr we will get 30. So *ptr=40 means change value stored at address 6234 (30) to 40. So at that place 40 will be replaced.

Chain of pointers
If we want to store address of pointer we can use chain of pointer as shown below: int no=30; int *ptr1; /*pointer to integer*/ int **ptr2 /*pointer to pointer*/ ptr1=&no; /*storing address of no in ptr1*/ ptr2 = &ptr1; /* storing address of ptr1 in ptr2 */ and by writing; printf(%d,**ptr2) it will print 30;ssss So ptr1 is a pointer to integer and ptr2 is a pointer to pointer or ptr2 is a pointer to pointer to integer.

Generic pointers
It is possible that one pointer variable can store address of different type of variable at different point of time by using

Prof. Chirag I Patel BCA Dept.

D. D. University Nadiad

Programming in C

Chapter-11,12

single pointer. This kind of pointer is known as generic pointer. For example: int no=40; float ans=90.100; void *vp; vp=&no; vp=&ans; So at one time vp has the address of no and another time vp has the address of ans. So vp is known void pointer or generic pointer as it can have address of any type of variable.

Pointers and arrays


Refer to class discussions

Pointers and strings


Refer to class discussions

Array of pointers
Refer to class discussions

Pointer as function arguments or passing by address or passing by pointer or pass by reference


Refer to class discussions

Pointers and structures


Refer to class discussions. Important point var = *&var. For example: int no=10; printf(%d,no); printf(%d,*&no); both lines will print 10 (value of no). So no=*&no

Useful Questions
Q.1. Show the output of following: int no=60; printf(%d,*&no); Ans: 60 Q.2. Show the output of the following: float ans=679; float *ptr=&ans; Prof. Chirag I Patel BCA Dept. 5 D. D. University Nadiad

Programming in C printf(%d,sizeof(ptr)); Ans: 2 (bytes) Q.3. Show the output of following: int no=100; int *ptr=&no; printf(%d,*ptr); Ans: 100 Q.4. Show the output of following: int no=2200; int *ptr=&no; printf(%u,ptr); Ans: Address of no Q.5. Show the output of following: int no=2200; int *ptr=&no; int *ptr2=&ptr; printf(%u,*ptr2); Ans: Address of no Q.6. Show the output of following: int no=2200; int *ptr=&no; printf(%u,*&ptr1); Ans: Address of no Q.7. Show the output of following: int no=2200; int *ptr=&no; int *ptr2=&ptr; printf(%d,**ptr2); Ans: 2200 (value of no)

Chapter-11,12

File Management In C
Introduction
We are reading data from screen and writing data to the screen by using various input and output method. But what if we want to save the data for the future use. For that concept of file has been introduced. What is file? Ans: A file is a place on the disk where the data is stored in particular format. Basic file operations include: 1. Naming a file 2. Opening a file 3. Reading data from file. 4. Writing data to file 5. Closing a file.

Defining and opening a file


If we want to store in file in the disk, we must specify certain things about file to the operating system. They include:
Prof. Chirag I Patel BCA Dept. 6 D. D. University Nadiad

Programming in C

Chapter-11,12

1. Filename is a group of characters. 2. Data Structure of file is FILE in C. 3. Purpose means for which purpose we need to open a file

i.e. for reading, writing or appending. Following is the syntax of declaring and opening a file. FILE *fp; fp=fopen(FileName, Mode); Here, fp is the pointer to file which is stored in the disk. We can perform all operations in the file by using fp. FileName is the name of path of file. Mode is the purpose of opening a file. Mode can be one of the following: Various opening modes/purpose of opening a file r Open file for reading w Open the file for writing a Open the file for appending Here FileName and Mode both must be enclosed by double quotes. When the mode is w and if file is not available then new file is created. But when the mode is w and if file is available then original contents of file are deleted. When the mode is a and if file is not available then new file is created. But when the mode is a and if file is available then existing contents will be as it is and new contents will be appended to the existing contents. When the mode is r and if file is available then new file is opened for reading other wise and error is generated.

Consider the following example: FILE * f1,*f2; f1=fopen(test1.txt,r); f2=fopen(test2.txt,w); Here test1.txt is opened for reading and test2.txt is opened for writing but if test1.txt does not exist then error will occur and if r+ File is opened for reading and writing test2.txt does w Same as w and for reading + writing not exist then + it will be a Same as a and for reading + writing created. + Many recent compilers include additional modes of operation as follows:

Closing a file
We can close a file by using fclose method. Syntax:

Prof. Chirag I Patel BCA Dept.

D. D. University Nadiad

Programming in C

Chapter-11,12

fclose (filepointer) However all the files are automatically once the C program terminates but it is a good programming practice to close a file after opening it.

Input/Output Operations on Files


We can read and write data to the file by various methods. Metho d putc getc putw getw fprintf fscanf Syntax putc(char variable, file pointer) Meaning

Writes a single character to the file char variable = getc(file Reads a single pointer) character from the file putw(int variable, file pointer) Write an integer to file int variable=getw(file pointer) Reads an integer from the file fprintf(file pointer, control Writes different string, list) types of data to the file. Similar to printf fscanf(file pointer, control Reads different string, list) types of data from the file. Similar to scanf

Error handing during file operations:


It is possible that an error can occur while reading or writing to the file. Common errors are listed here: 1. Trying to go beyond EOF 2. Device overflow 3. Using a file which is not opened 4. Mismatch of operation. 5. Opening file with invalid name. 6. Trying to write in read only file. To check EOF error we can use feof method as follows: if (feof(fp)) printf(End of file is reached); To check whether file has been opened or not, we can check value of fp. If value of fp is NULL then either file name is not correct or some how we are not able to open the file. The code segment is as follows: if (fp==NULL) printf(Not able to open file); For other I/O errors we can check ferror method, which returns non-zero value if there is an error in doing any of the file operations. The code segment is as follows: if (ferror(fp)!=0) printf(Error has occurred);

Prof. Chirag I Patel BCA Dept.

D. D. University Nadiad

Programming in C

Chapter-11,12

Random Access to the files


To read data or write data in the file from or at any position(Random Access) we can use following methods: 1.ftell(): Returns current position of file pointer in a file in terms of bytes. Return type is long Syntax is: n=tell(fp) 2.rewind(): Sets the file pointer to the beginning of the file. For example: rewind(fp); n=ftell(fp); will store 0 in n as rewind is taking file pointer to the beginning of the file. 3.fseek(): It is used to move file pointer at desired position. Syntax is: fseek(file_ptr, offset, position) Here, file_ptr is the pointer to the related file. offset is a variable or constant of type to indicate how many bytes we need to move. Positive value of offset means forward direction and negative value of offset means backward direction.
Statement fseek(fp,0L,0) fseek(fp,0L,1) fseek(fp,10L,0) fseek(fp,10L,1) fseek(fp,-10L,1) fseek(fp,-10L,2) Meaning Go to beginning of file(same as rewind) Stay at current position Move 10 bytes forward from the beginning(Go to 11th byte) Move 10 bytes forward from the current position Move 10 bytes backward from the current position Move 10 bytes backward from the end of file

position means from which point we need to start. Values of position:


Value 0 1 2 Meaning Beginning of file Current position End of File

Examples of fseek method

Command Line Arguments


Command line is a parameter that is supplied to program when program is invoked. So when we want to make our program just like a command we can use command line arguments facility available in C. For that we need to write main function in following manner: main(int argc, char *argv[]) { . . } Here argc contains number of arguments and argv contains list of the arguments. So: argv[0] contains program name

Prof. Chirag I Patel BCA Dept.

D. D. University Nadiad

Programming in C

Chapter-11,12

argv[1] contains argument1 argv[2] contains argument2 argv[n] contains argumentn The first parameter in the command line is always the program name therefore argv[0] always contains program name.

Prof. Chirag I Patel BCA Dept.

10

D. D. University Nadiad

Вам также может понравиться