0% found this document useful (0 votes)
10 views33 pages

C Language Ch5

This document discusses pointers and file structures in C language. It introduces memory and how variables are stored in memory cells with addresses. Pointer is defined as a variable that stores the address of another variable. The key features of pointers are also described. The document explains pointer declaration syntax, initialization, accessing variable values using pointers, pointer arithmetic, pointers to arrays, strings, structures, and double pointers. It also covers passing pointers as function arguments, pointers within structures, and dynamic memory allocation functions like malloc(), calloc(), and realloc() for allocating memory at runtime.

Uploaded by

mihirbhuva1
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
10 views33 pages

C Language Ch5

This document discusses pointers and file structures in C language. It introduces memory and how variables are stored in memory cells with addresses. Pointer is defined as a variable that stores the address of another variable. The key features of pointers are also described. The document explains pointer declaration syntax, initialization, accessing variable values using pointers, pointer arithmetic, pointers to arrays, strings, structures, and double pointers. It also covers passing pointers as function arguments, pointers within structures, and dynamic memory allocation functions like malloc(), calloc(), and realloc() for allocating memory at runtime.

Uploaded by

mihirbhuva1
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 33

C language

Unit – 5
Pointer & File structure
Introduction of Memory
Memory is a sequential collection of memory cells, which
are in bytes, associated with their address.
The first address of memory cell is 0, and last address
depends on size of memory.
When we declare any variable in our program, they are
stored in these memory cells. Memory cell (in bytes) Address
0
1
2
.
.
.
65535
Pointer
“Pointer is a variable which can store address of another
variable.”
Pointer is derived data type like array & structure.
Address is a location in in memory where data are stored,
and pointer is used to access that data.
Features or Benefits of Pointer:
(1) pointers are more efficient to handle arrays.
(2) pointer to character string array saves space.
(3) using pointer, C supports Dynamic memory allocation.
(4) They increase the execution speed and thus reduce the
program execution time.
Declaration of pointer:
Data_type *pointer_name;
“*” this is called pointer sign, which shows that the variable is
a pointer variable.
The above declaration tells the compiler that *pointer_name is
a pointer variable, which can store address of type “data_type”.
For example, in int *p, *p is a pointer variable, which can store
address of int type variable.
Initialization of pointer:
 Pointer_variable = & variable; Variable A p

Example : Value 10 1000


 Int a=10, *p; // declaration Address 1000
 P=&a; //initialization
Assigning address of variable to pointer is called pointer
initialization.
Accessing Value of variable using pointer:
After initialization of pointer, we can use pointer for
following:
P means the address of a.
*P means the value of a. (value at address)

Variable Meaning
a Values of a
&a Address of a
*p Value of a
P Address of a

Note : format specifier %u is used to print an address.


Arithmetic Pointer
(or Pointer Expression)
Like other variables, pointer variables can be used in
expressions.
Example:
Int a=10, b=20,*pa,*pb,sum;
Pa=&a;
Pb=&b;
Sum = *pa + *pb ; // same as a+b
Pointer to Array
When we use array, the location of first element (index
0) is called base address.
We can use pointer, to point to the array by assigning
base address of array to pointer.
Example :
Int x[5]={1,2,3,4,5};
Int *p;
P= x[0]; or p=x;
Index no X[0] X[1] X[2] X[3] X[4]
Value 1 2 3 4 5
Address 1000 1002 1004 1006 1008
 p
1000
Now, we can access every value of x using p++ to move
from one element to another. The relationship
between p and x is shown as:
 p = &x[0] (=1000)
 p+1=&x[1] (=1002)
 p+2=&x[2] (=1004)
 p+3=&x[3] (=1006)
 p+4=&x[4] (=1008)

Note that *(p+3) gives the value of x[3].


Pointer to character array (string)
As we know that, a string is an array of characters,
which is declared & initialize as follow:
Char str[10] = “Good”;
0 1 2 3 4 5 6 7 8 9
G O O D \0
Str
This will automatically store NULL (\0) to the end of
string.
If we want to create pointer to this string, we can store
the base address (&str[0]) to pointer;
Char *p=&str[0];
Instead of this, we also can do following:
Char *str = “Good”;
Array of pointer
We can use array of pointer for string table.
Consider the following example:
Char name[3][10];
The above example shows that “name” is a table which
can store 3 names, each with maximum length of 10
characters. So, total bytes required are 30(3*10).
0 1 2 3 4 5 6 7 8 9
Name[0]
Name [1]
Name[2]
To access this, we have to use 2 dimension array.
Instead of using 2-D array, we can use array of pointer,
because each pointer variable can access whole string.
For example:
char *name[3] = {“ajay”, ”hardik”, “vishal”};
Now , we can access each string like:
Name [0] = “ajay”;
Name [1] = “hardik”;
Name [2] = “vishal”;
This will use only 19 bytes.
If we want to access “r”, we can write *(name[1]+2).
Pointer as function argument
we can pass the address of a variable as an argument to a
function, which is called “call by reference”.
When function receives this “reference”, it points to the actual
variable. It can make changes on actual value of passed variable.
Syntax for passing reference: (& variable)
Syntax for receiving address: (datatype * pointername)
Example:
 Main ()
 { int x=20;
 Change (&x); //pass reference of x
 Printf (“x= %d”,x);
 }
 Change (int *p) //receives reference
 { *p=*p+10; //change the value of x
 }
Pointer to structure
Like array, we can use a pointer to point a structure.
For this, we have to create a pointer of type structure.
For example:
Struct stud
{ int rno;
 char name[10];
}s1,*p;
Main()
{ p=&s1;
}
In above example, pointer *p points to the structure variable
s1.
Now, we can access the data members of structure
using pointer like this:
P->rno;
P->name;
The -> operator is called arrow operator or “pointer to
member” operator.
Pointer within structure
We can use pointer as a member of structure, which is
used to point individual data member of structure.
Example :
Struct stud
{ int rno, *pr;
 char name[10];
}s1;
Pr=&s1.rno;
Now, we can access rno using its pointer pr.
S1.*pr;
Pointer to pointer (Double pointer)
We can store the address of pointer variable in another pointer,
which is called pointer to pointer.
Variable P1 P2
value Address1 Address2

In above example, pointer p2 contains the address of pointer p1,


and p1 contains the address of variable.
P2 is a pointer to pointer variable, which can be declared as : int
*p1,**p2;
For p2, we have to use additional * sign.
This declaration tells the compiler that p2 is a pointer to a pointer
of int type.
Now, to access the value of variable, we can write **p2.
Example:
Printf (“Value = %d”,**p2);
Rules for pointer
 Only an address of a variable can be stored in pointer variable.
 Do not store the address of variable of one type into a pointer variable of another
type.
 The value of a variable cannot be assigned to a pointer variable.
 A pointer variable contain garbage until it is initialized therefore we must not use a
pointer variable before it is assigned the address of a variable.
 When we pass a parameter by address the corresponding formal parameter must
be a pointer variable.
 It is an error to assign a numeric constant to a pointer variable.
 It is an error to assign the address of a variable to a variable of any basic dat5a
type.
 A proper understanding of a precedence and associativity rules is very important
in pointer applications.
 When an array is passed as an argument to a function a pointer is actually passed.
 A very common error is to use (or not to use) the address operator (&) and the
indirection operator (*) in certain place. Be careful. The compiler may not warn
such mistakes.
Dynamic memory allocation (DMA)
The process of allocating memory at run time is known as
dynamic memory allocation.
DMA permits us to specify the size of array at run time. So,
during the execution of program, we can allocate additional
memory to an array variable.
There are 4 library functions which can be used for allocating &
freeing memory during execution. These functions are called
“Memory management Functions.”
1. Malloc()
2. Calloc()
3. Realloc()
4. Free()
(1) Malloc():
 The malloc function reserves a block of memory of specified size and
return a pointer of type void. This means that we can assign it to any
type of pointer.
 Syntax :
 ptr=(datatype*) malloc(size in bytes);
 Ptr is a pointer of type datatype. The malloc returns an address to an
area of memory with size byte-size.
 Example :
 P=(int*) malloc(5 * sizeof(int));
 Above example will calculate & reserves “5 times the size of int” in
bytes, and allocate the address of first byte to pointer p. there is no
name of array.
P [0] [1] [2] [3] [4]
Address
(2) calloc ():
Calloc is another function which is used for requesting
memory space at run time for storing array.
Malloc allocates single block and calloc allocates multiple
blocks, each of same size.
Syntax :
Ptr= (datatype*) calloc (n,elem_size);
The above statement allocates contiguous space for n blocks,
each of size elem-size bytes. All bytes are initialized to zero
and a pointer to the first byte of the allocated region is
returned.
Example :
P=(int*) calloc (5,sizeof(int));
This will multiply 5*2 and allocate 10 blocks for int. it will
store the address of first block into P.
Differences : malloc() v/s calloc()
Malloc Calloc
1 It allocates single block of It allocates multiple
storage. blocks of storage of same
size.
2 Initialize with garbage Initialize with zero (0).
value
(3) realloc():
This function is used to change the size of allocated
memory at runtime, specified by malloc or calloc
functions.
Using realloc(), we can increase or decrease the size of
memory at runtime.This is called reallocation of
memory.
Example :
P=malloc(size);
P=realloc(new size);
If the new size is larger than old size, the additional
blocks will be added to the end of previously allocated
space. The old data remains same.
(4) free():
With the dynamic run-time allocation, it is our
responsibility to release the space when it is not
required. So that, we can use it for future use.
Free() is used to release memory, allocated by malloc
or calloc functions.
Syntax : free (pointer variable);
This will release memory to which “pointer” points to.
Importance of pointer in DMA
When we ask the computer to allocate the memory
dynamically, it allocates an array memory and gives the
address of it.
This address is given to pointer.
The functions used for DMA, returns address of
memory which is stored in pointer.
There is no name of name of this memory. So, we can
use this memory through the pointer. We can set
values in memory and get values from memory using
pointer only.
Introduction of File
A Data file is a container used for storing data.
Or
File is a place on the disk where a group of related data can be
stored.
If you have to enter a large number of data, we can use a file
containing all the data. Whenever necessary, we can read these
data without destroying it.
 you can easily access the contents of the file using a few
commands in C.
There are two types of file.
(1) text file
(2) binary file
(1) text file:
Text files are the normal .txt files. You can easily
create text files using any simple text editors such as
Notepad.
When you open those files, you'll see the file as plain
text. You can easily edit or delete the contents.
(2) binary file:
Binary files are mostly .bin files.
It contains the data in binary form (0 & 1).
These files are not readable easily, but provides better
security than text file.
File handling
“File Handling is the storing of data in a file using a
program.”
These programs stores results and other data of program in
to a file using file handling.
We also can get data from file and work on it.
C provides following operations for file handling:
1. Creating a new file
2. Opening an existing file
3. Reading data from file
4. Writing data to file
5. Moving data from one file to another
6. Closing a file.
File handling functions
no Function name Use example
1 fopen(filename,mode): creates a new file for use or Fp=fopen(“abc.txt”,”r”);
opens an existing file for use.

2 fclose(file pointer) closes a file which has been Fclose (fp)


opened for use.
3 getc(file name) reads a character from a file. Char ch;
Ch =getc(fp);
4 putc(char, file pointer) writes a character to a file. Putc(ch,fp)

5 getw(file name) reads an integer from a file. Int a;


a= getw(fp)

6 putw() writes an integer to a file. Putw(int,fp)


no Function name Use Example
7 fprintf(file writes a set of data values Fprintf(fp,”welcome”)
pointer,data,variable) from a file. Fprintf(fp,”%d”,a);

8 Fscanf (file pointer, reads a set of data values Fscanf(fp,”%d”,&no)


data, variable) from a file.

9 fseek(file sets the position to a desired Fseek(fp,10,o)


pointer,offset,position) point in the file.

10 ftell(file pointer) fives the current position in Ftell (fp)


the file.

11 rewind(file pointer) sets the position to the Rewind(fp)


beginning of the file.
Command line argument
command line argument is a parameter supplied to a
program when the program starts execution.
This parameter may represent a filename the program
should process. For Example, if we want to execute a
program to copy the contents of a file named abc to
another one named xyz, then we may use a command
line like:
Example : PROGRAM ABC XYZ
where PROGRAM is the filename where the
executable code of the program is stored.
When main function is called, it can take two arguments called
argc and argv.
The information contained in the command line is passed on to
the program through these arguments.
Example : main (int argc, char *argv[])
The variable argc is an argument counter that counts the
number of arguments on the command line. The size of this
array will be equal to the value of argc.
The argv is an array of character pointers that point to the
command line arguments.
for above example,
argv[0] -> PROGRAM
argv[1] -> ABC
argv[2] -> XYZ
The first argument is always a filename, stored in argv[0].
Assignment – 5 (pointer)
Q. No Questions Marks
1 What is pointer? How it can be used? 3
2 Explain pointer arithmatic. 3
3 Explain pointer to Array. 5
4 Explain pointer to character string. 3
5 Explain array of pointer. 5
6 Explain pointer to structure with example. 3
7 Explain double pointer with example. 3

8 Explain how to use pointer as a function argument. 3


9 Explain use of DMA in detail. 5
10 Explain the importance of pointer in DMA? 5
Assignment – 6 (file handling)
Q. No Questions Marks
1 What is data file? Explain types of data file. 3
2 What is the importance of file handling in c. 3
3 Explain file handling functions. 3
4 Explain command line argument with example. 5

You might also like