11 - Pointers and Files
11 - Pointers and Files
1
Basics of Pointers
2
Introduction
A pointer is a variable that represents the location (rather than the value) of a data item.
3
Basic Concept
In memory, every stored data item occupies one or more contiguous memory cells.
• The number of memory cells required to store a data item depends on its type (char, int, double, etc.).
Whenever we declare a variable, the system allocates memory location(s) to hold the value of the variable.
• Since every byte in memory has a unique address, this location will also have its own (unique) address.
4
Example
1380
(xyz) 50
Consider the statement
int xyz = 50;
• This statement instructs the compiler to allocate a location for the integer variable xyz, and
put the value 50 in that location.
• The value 50 can be accessed by using either the name xyz or the address 1380.
5
Example (Contd.)
1380
(xyz) 50
int xyz = 50;
int *ptr; // Here ptr is a pointer to an integer ----
(ptr)
1380
ptr = &xyz;
Since memory addresses are simply numbers, they can be assigned to some variables which can be stored in
memory.
• Such variables that hold memory addresses are called pointers.
• Since a pointer is a variable, its value is also stored in some memory location.
6
Pointer Declaration
A pointer is just a C variable whose value is the address of another variable!
int *ptr;
ptr doesn’t actually point to anything yet.
We can either:
7
Making it point
8
Accessing the Address of a Variable
The address of a variable can be determined using the ‘&’ operator.
• The operator ‘&’ immediately preceding a variable returns the address of the variable.
Example:
p = &xyz;
• The address of xyz (1380) is assigned to p.
The ‘&’ operator can be used only with a simple variable or an array element.
&distance
&x[0]
&x[i-2]
9
Illegal usages
Following usages are illegal:
&235
• Pointing at constant.
int arr[20];
:
&arr;
• Pointing at array name.
&(a+b)
• Pointing at expression.
10
Pointer Declarations and Types
General form:
data_type *pointer_name;
11
Pointers have types
Example:
int *count;
float *speed;
Once a pointer variable has been declared, it can be made to point to a variable using an assignment statement like:
int *p, xyz;
:
p = &xyz;
• This is called pointer initialization.
12
Things to remember
Pointer variables must always point to a data item of the same type.
float x;
int *p;
p = &x; // This is an erroneous assignment
int *count;
count = 1268;
13
Pointer Expressions
Like other variables, pointer variables can be used in expressions.
14
More on pointer expressions
What are allowed in C?
• Add an integer to a pointer.
• Subtract an integer from a pointer.
• Subtract one pointer from another
• If p1 and p2 are both pointers to the same array, then p2–p1 gives the number of elements between
p1 and p2.
15
More on pointer expressions
16
Scale Factor
We have seen that an integer value can be added to or subtracted from a pointer variable.
p = &x[1];
printf( “%d”, *p); // This will print 20
17
More on Scale Factor
struct complex {
float real;
float imag;
};
struct complex x[10];
p = &x[0]; // The pointer p now points to the first element of the array
The increment of p is not by one byte, but by the size of the data type to which p points.
This is why we have many data types for pointers, not just a single “address” data type
18
Pointer types and scale factor
Data Type Scale Factor
char 1
int 4
float 4
double 8
19
Scale factor may be machine dependent
• The exact scale factor may vary from one machine to another.
• Can be found out using the sizeof function.
#include <stdio.h>
main( )
{
printf (“No. of bytes occupied by int is %d \n”, sizeof(int));
printf (“No. of bytes occupied by float is %d \n”, sizeof(float));
printf (“No. of bytes occupied by double is %d \n”, sizeof(double));
printf (“No. of bytes occupied by char is %d \n”, sizeof(char));
}
Output:
Number of bytes occupied by int is 4
Number of bytes occupied by float is 4
Number of bytes occupied by double is 8
Number of bytes occupied by char is 1
20
Passing Pointers to a Function
Pointers are often passed to a function as arguments.
• Allows data items within the calling program to be accessed by the function, altered, and then returned
to the calling program in altered form.
• Called call-by-reference (or by address or by location).
21
Passing arguments by value or reference
#include <stdio.h> #include <stdio.h>
main( ) main( )
{ {
int a, b; int a, b;
a = 5; b = 20; a = 5; b = 20;
swap (a, b); swap (&a, &b);
printf (“\n a=%d, b=%d”, a, b); printf (“\n a=%d, b=%d”, a, b);
} }
void swap (int x, int y) void swap (int *x, int *y)
{ {
int t; int t;
t = x; x = y; y = t; t = *x; *x = *y; *y = t;
} }
Output Output
a=5, b=20 a=20, b=5
22
Pointers and Arrays
• The compiler allocates a base address and sufficient amount of storage to contain all the elements of the
array in contiguous memory locations.
• The base address is the location of the first element (index 0) of the array.
• The compiler also defines the array name as a constant pointer to the first element.
23
Example
• Suppose that the base address of x is 2500, and each integer requires 4 bytes.
24
Example (contd)
Both x and &x[0] have the value 2500.
p = x; and p = &x[0]; are equivalent
• We can access successive values of x by using p++ or p-- to move from one element to another.
25
Arrays and pointers
26
27
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Arrays
Consequences:
• ar is a pointer
• ar[0] is the same as *ar
• ar[2] is the same as *(ar+2)
• We can use pointer arithmetic to access arrays more
conveniently.
28
Arrays In Functions
An array parameter can be declared as an array or a pointer; an array argument can be passed as a pointer
} }
29
Arrays and pointers
When an array is declared the compiler allocates a sufficient amount of contiguous space in memory. The base
address of the array is the address of a[0].
Suppose the system assigns 300 as the base address of a. a[0], a[1], ...,a[19] are allocated 300, 304, ..., 376.
30
Arrays and pointers
#define N 20
p = a; is equivalent to p = &a[0];
p is assigned 300.
p=a;
for (p=a; p<&a[N]; ++p) sum += *p ; for (i=0; i<N; ++i) sum += p[i] ;
31
Arrays and pointers
int a[N];
a is a constant pointer.
32
Pointer arithmetic and element size
double * p, *q ;
The expression p+1 yields the correct machine address for the next variable of that type.
• p+i
• ++p
• p+=i
• p-q /* No of array elements between p and q */
33
Pointer Arithmetic
• x = *p++ ⇒ x = *p ; p = p + 1;
• x = (*p)++ ⇒ x = *p ; *p = *p + 1;
• C takes care of it: In reality, p+1 doesn’t add 1 to the memory address, it adds the size of the array
element.
34
Pointer Arithmetic
We can use pointer arithmetic to “walk” through memory:
° C automatically adjusts the pointer by the right amount each time (i.e., 1 byte for a char, 4 bytes for an int,
etc.)
35
Arrays of Structures
We can define an array of structure records as
struct stud class[100];
36
Pointers and Structures
Once ptr points to a structure variable, the members can be accessed as:
ptr –> roll;
ptr –> dept_code;
ptr –> cgpa;
37
A Warning
When using structure pointers, we should take care of operator precedence.
• Member operator “.” has higher precedence than “*”.
ptr –> roll and (*ptr).roll mean the same thing.
*ptr.roll will lead to error.
38
Use of pointers to structures
#include <stdio.h>
struct complex {
float real;
float imag; void add (x, y, t)
}; struct complex *x, *y, *t;
{
main( )
{ t->re = x->real + y->real;
struct complex a, b, c; t->im = x->imag + y->imag;
scanf ( “%f %f”, &a.real, &a.imag ); }
scanf ( “%f %f”, &b.real, &b.imag );
add( &a, &b, &c ) ;
printf ( “\n %f %f”, c,real, c.imag );
}
39
Dynamic Memory Allocation
40
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Basic Idea
Such situations can be handled more easily and effectively using dynamic memory management techniques.
41
Dynamic Memory Allocation
42
Memory Allocation Process in C
Heap
Free memory
Global variables
Permanent storage area
Instructions
43
Memory Allocation Process
The program instructions and the global variables are stored in a region known as permanent storage area.
The memory space between these two areas is available for dynamic allocation during execution of the program.
• This free region is called the heap.
• The size of the heap keeps changing.
44
Memory Allocation Functions
malloc
• Allocates requested number of bytes and returns a pointer to the first byte of the allocated space.
calloc
• Allocates space for an array of elements, initializes them to zero and then returns a pointer to the memory.
free
• Frees previously allocated space.
realloc
• Modifies the size of previously allocated space.
45
Allocating a Block of Memory
A block of memory can be allocated using the function malloc.
• Reserves a block of memory of specified size and returns a pointer of type void.
• The return pointer can be type-casted to any pointer type.
General format:
ptr = (type *) malloc (byte_size);
46
Continued
Examples
p = (int *) malloc(100 * sizeof(int));
• A memory space equivalent to 100 times the size of an int bytes is reserved.
• The address of the first byte of the allocated memory is assigned to the pointer p of type int.
47
Contd.
• Allocates space for a structure array of 10 elements. sptr points to a structure element of type “struct stud”.
48
Points to Note
malloc always allocates a block of contiguous bytes.
• The allocation can fail if sufficient contiguous memory space is not available.
• If it fails, malloc returns NULL.
49
Releasing the Used Space
When we no longer need the data stored in a block of memory, we may release the block for future use.
How?
• By using the free function.
General syntax:
free (ptr);
where ptr is a pointer to a memory block which has been previously created using malloc.
50
Altering the Size of a Block
Sometimes we need to alter the size of some previously allocated memory block.
• More memory needed.
• Memory allocated is larger than necessary.
How?
• By using the realloc function.
51
Contd.
• The new memory block may or may not begin at the same place as the old one.
• If it does not find space, it will create it in an entirely different region and move the contents of the
old block into the new block.
52
Arrays of Pointers
53
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Static array of pointers
#define N 20
#define M 10
int main()
{
char word[N], *w[M];
int i, n;
scanf("%d",&n);
for (i=0; i<n; ++i) {
scanf("%s", word);
w[i] = (char *) malloc ((strlen(word)+1)*sizeof(char));
strcpy (w[i], word) ;
}
for (i=0; i<n; i++) printf("w[%d] = %s \n",i,w[i]);
return 0;
}
54
Static array of pointers
#define N 20
Input / Output
#define M 10
int main() 4
{ Tendulkar
char word[N], *w[M]; Sourav
int i, n; Khan
scanf("%d",&n); India
for (i=0; i<n; ++i) { w[0] = Tendulkar
scanf("%s", word); w[1] = Sourav
w[i] = (char *) malloc ((strlen(word)+1)*sizeof(char)); w[2] = Khan
strcpy (w[i], word) ; w[3] = India
}
for (i=0; i<n; i++) printf("w[%d] = %s \n",i,w[i]);
return 0;
}
55
How it will look like
w
0 T e n d u l k a r \0
1 S o u r a v \0
2 K h a n \0
3 I n d i a \0
56
Pointers to pointers
• Pointers are also variables (storing addresses), so they have a memory location, so they also have an address
• Pointer to pointer – stores the address of a pointer variable
57
Allocating pointer to pointer
int **p;
p = (int **) malloc(3 * sizeof(int *));
p[0]
p int ** int *
p[1] int *
p[2] int *
58
Dynamic arrays of pointers
int main()
Output
{
char word[20], **w; /* “**w” is a pointer to a pointer array */ 5
int i, n; India
scanf("%d",&n); Australia
w = (char **) malloc (n * sizeof(char *)); Kenya
for (i=0; i<n; ++i) { NewZealand
scanf("%s", word); SriLanka
w[i] = (char *) malloc ((strlen(word)+1)*sizeof(char)); w[0] = India
strcpy (w[i], word) ; w[1] = Australia
} w[2] = Kenya
w[3] = NewZealand
for (i=0; i<n; i++) printf("w[%d] = %s \n",i, w[i]);
w[4] = SriLanka
return 0;
}
59
How this will look like
w 0 I n d i a \0
1 A u s t r a l I a \0
2 K e n y a \0
3 N e w Z e a l a n d \0
4 S r i L a n k a \0
60
Data Type of 2-D Array
#include <stdio.h>
int main( )
{
int matrix[4][3] = { {1, 2, 3}, OUTPUT
{4, 5, 6}, =======
{7, 8, 9}, &matrix[0][0] = 1245016
{10, 11, 12}}; &pmat[0][0] = 1
int** pmat = (int **)matrix;
Why are they different?
printf("&matrix[0][0] = %u\n", &matrix[0][0]);
printf("&pmat[0][0] = %u\n", &pmat[0][0]);
return 0;
}
61
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
2D Arrays and Pointers
#define COL 5
int y[5][COL];
int x = *(y + 2*COL + 2);
This is not correct !!
#define COL 5
int y[5][COL];
int x = *((int *)y + 2*COL + 2);
This is correct!!
62
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Dynamic Allocation of 2D array
#include <stdio.h>
#include <stdlib.h>
#define ROW 3
20
#define COL 4
int main()
This creates a list of pointers
{
int count;
This creates each row
int **arr = (int **) malloc(ROW * sizeof(int *));
for (i=0; i<ROW; i++) arr[i] = (int *)malloc(COLUMN * sizeof(int));
arr[2][3] = 20; // Note that the style of accessing is the same
}
63
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
We could use one malloc( ) call for all the rows
#include<stdio.h>
#include<stdlib.h>
#define ROW 3 20
#define COL 4
int main( )
{
int **arr;
int i, j;
64
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Dynamic allocation of 2-D Arrays
int **allocate (int h, int w)
{ void read_data (int **p, int h, int w)
int **p; Allocate array {
int i, j; of pointers int i, j;
for (i=0;i<h;i++)
p = (int **) malloc(h*sizeof (int *) ); for (j=0;j<w;j++)
for (i=0;i<h;i++) scanf ("%d", &p[i][j]);
p[i] = (int *) malloc(w * sizeof (int)); }
return(p);
} Elements accessed
Allocate array of
like 2-D array elements.
integers for each
row
65
Dynamic allocation of 2-D Arrays
int main()
void print_data (int **p, int h, int w)
{ Give M and N
{
int **p; 33
int i, j;
int M, N; 123
for (i=0;i<h;i++)
printf ("Give M and N \n"); 456
{
scanf ("%d%d", &M, &N); 789
for (j=0;j<w;j++)
p = allocate (M, N); The array read as
printf ("%5d ", p[i][j]);
read_data (p, M, N); 1 2 3
printf ("\n");
printf ("\nThe array read as \n"); 4 5 6
}
print_data (p, M, N); 7 8 9
}
return 0;
}
66
Memory layout in dynamic allocation
int main() int **allocate (int h, int w)
{ {
int **p;
int **p;
int M, N;
int i, j;
printf ("Give M and N \n");
scanf ("%d%d", &M, &N);
p = (int **)malloc(h*sizeof (int *));
p = allocate (M, N);
for (i=0; i<h; i++) printf(“%10d”, &p[i]);
for (i=0;i<M;i++) {
for (j=0;j<N;j++) printf(“\n\n”);
printf ("%10d", &p[i][j]); for (i=0;i<h;i++)
printf(“\n”); p[i] = (int *)malloc(w*sizeof(int));
}
return(p);
return 0;
}
}
67
Output
68
File Handling
69
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
What is a file?
A named collection of data, stored in secondary storage (typically).
70
File Types
• The last byte of a file contains the end-of-file character (EOF), with ASCII code 1A (hex).
• While reading a text file, the EOF character can be checked to know the end.
71
File handling in C
In C we use FILE * to represent a pointer to a file.
fopen is used to open a file. It returns the special value NULL to indicate that it is unable to open the file.
FILE *fptr;
char filename[ ]= "file2.dat";
if (fptr == NULL) {
printf (“ERROR IN FILE CREATION”);
/* DO SOMETHING */
}
72
Modes for opening files
The second argument of fopen is the mode in which we open the file. There are three modes.
"w" creates a file for writing, and writes over all previous contents (deletes the file so be careful!).
"a" opens a file for appending – writing on the end of the file.
73
Binary Files
We can add a “b” character to indicate that the file is a binary file.
• “rb”, “wb” or “ab”
74
The exit( ) function
exit(0);
exits the program
75
Usage of exit( )
FILE *fptr;
char filename[ ]= "file2.dat";
fptr = fopen (filename,"w");
if (fptr == NULL) {
printf (“ERROR IN FILE CREATION”);
exit(0);
}
76
Writing to a file using fprintf( )
77
Reading Data Using fscanf( )
int x, y;
FILE *fptr;
fptr = fopen (“input.dat”, “r”);
78
Reading lines from a file using fgets( )
We can read a string using fgets().
FILE *fptr;
char line [1000];
…… /* Open file and check it is open */
while (fgets(line, 1000, fptr) != NULL)
{
printf (“We have read the line: %s\n", line);
}
fgets( ) takes 3 arguments – a string, maximum number of characters to read, and a file pointer.
It returns NULL if there is an error (such as EOF).
79
Closing a file
We can close a file simply using fclose() and the file pointer.
FILE *fptr;
char filename[ ]= "myfile.dat";
if (fptr == NULL) {
printf ("Cannot open file to write!\n");
exit(0);
}
80
Three special streams
Three special file streams are defined in the <stdio.h> header
• stdin reads input from the keyboard
• stdout send output to the screen
• stderr prints errors to an error device (usually also the screen)
81
An example program
Output:
Give value of i
15
#include <stdio.h> Value of i=15
main( ) No error: But an example to show error message.
{
int i;
82
Input File & Output File redirection
One may redirect the standard input and standard output to other files (other than stdin and stdout).
scanf() will read data inputs from the file “in.dat”, and printf() will output results on the file “out.dat”.
83
A Variation
$ ./a.out <in.dat >>out.dat
scanf() will read data inputs from the file “in.dat”, and printf() will append results at the end of the file “out.dat”.
84
Reading and Writing a character
A character reading/writing is equivalent to reading/writing a byte.
int getchar( );
stdin, stdout
int putchar(int c);
Example:
char c;
c = getchar();
putchar(c);
85
Command Line Arguments
86
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
What are they?
A program can be executed by directly typing a command at the operating system prompt.
$ cc –o test test.c
$ ./a.out in.dat out.dat
$ prog_name param_1 param_2 param_3 ..
• The individual items specified are separated from one another by spaces.
• First item is the program name.
• Variables argc and argv keep track of the items specified in the command line.
87
How to access them?
Command line arguments may be passed by specifying them under main().
88
$ ./a.out s.dat d.dat
argc=3 ./a.out
s.dat
d.dat
argv
89
Example: Program for Copying a File
#include <stdio.h>
#include <string.h>
if (argc!=3) {
printf ("Usage: ./a.out <src_file> <dst_file> \n"); exit(0);
}
else {
strcpy (src_file, argv[1]); strcpy (dst_file, argv[2]);
}
90
Example: contd.
if ((ifp = fopen(src_file,"r")) == NULL) {
printf (“Input File does not exist.\n"); exit(0);
}
while ((c = fgetc(ifp)) != EOF) fputc (c,ofp); // This is where the copying is done
fclose(ifp); fclose(ofp);
}
91
Practice problems
• Take any of the problems you have done so far using 1-d arrays or 2-d arrays. Now do them by allocating the
arrays dynamically first instead of declaring then statically
92