Download presentation
Presentation is loading. Please wait.
1
Programming and Data Structure
PDS Class Test 2 Date: October 27, 2016 Time: 7pm to 8pm Marks: 20 (Weightage 50%) Room Sections No of students V1 Section 8 (All) Section 9 (AE,AG,BT,CE, CH,CS,CY,EC,EE,EX) 101 49 V2 Section 9 (Rest, if not allotted in V1) Section 10 (All) 50 98 V3 Section 11 (All) V4 Section 12 (All) 94 F116 Section 13 (All) 95 F142 Section 14 (All) 96 Autumn 2016 Programming and Data Structure
2
Programming and Data Structure
Pointers Part 2 Autumn 2016 Programming and Data Structure
3
Programming and Data Structure
Introduction A pointer is a variable that represents the location (rather than the value) of a data item. They have a number of useful applications. Enables us to access a variable that is defined outside the function. Can be used to pass information back and forth between a function and its reference point. More efficient in handling data tables. Reduces the length and complexity of a program. Sometimes also increases the execution speed. Autumn 2016 Programming and Data Structure
4
Programming and Data Structure
Pointers and Arrays When an array is declared, 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. Autumn 2016 Programming and Data Structure
5
Programming and Data Structure
Structures Revisited Recall that a structure can be declared as: struct stud { int roll; char dept_code[25]; float cgpa; }; struct stud a, b, c; And the individual structure elements can be accessed as: a.roll , b.roll , c.cgpa , etc. Autumn 2016 Programming and Data Structure
6
Programming and Data Structure
Arrays of Structures We can define an array of structure records as struct stud class[100] ; The structure elements of the individual records can be accessed as: class[i].roll class[20].dept_code class[k++].cgpa Autumn 2016 Programming and Data Structure
7
Example: Sorting by Roll Numbers
#include <stdio.h> struct stud { int roll; char dept_code[25]; float cgpa; }; main() struc stud class[100], t; int j, k, n; scanf (“%d”, &n); /* no. of students */ for (k=0; k<n; k++) scanf (“%d %s %f”, &class[k].roll, class[k].dept_code, &class[k].cgpa); for (j=0; j<n-1; j++) for (k=j+1; k<n; k++) { if (class[j].roll > class[k].roll) t = class[j] ; class[j] = class[k] ; class[k] = t } <<<< PRINT THE RECORDS >>>> Autumn 2016 Programming and Data Structure
8
Pointers and Structures
You may recall that the name of an array stands for the address of its zero-th element. Also true for the names of arrays of structure variables. Consider the declaration: struct stud { int roll; char dept_code[25]; float cgpa; } class[100], *ptr ; Autumn 2016 Programming and Data Structure
9
Programming and Data Structure
The name class represents the address of the zero-th element of the structure array. ptr is a pointer to data objects of the type struct stud. The assignment ptr = class ; will assign the address of class[0] to ptr. When the pointer ptr is incremented by one (ptr++) : The value of ptr is actually increased by sizeof(stud). It is made to point to the next record. Autumn 2016 Programming and Data Structure
10
Programming and Data Structure
Once ptr points to a structure variable, the members can be accessed as: ptr –> roll ; ptr –> dept_code ; ptr –> cgpa ; The symbol “–>” is called the arrow operator. Autumn 2016 Programming and Data Structure
11
Programming and Data Structure
Example #include <stdio.h> typedef struct { float real; float imag; } _COMPLEX; swap_ref(_COMPLEX *a, _COMPLEX *b) { _COMPLEX tmp; tmp=*a; *a=*b; *b=tmp; } main() { _COMPLEX x={10.0,3.0}, y={-20.0,4.0}; print(&x); print(&y); swap_ref(&x,&y); } print(_COMPLEX *a) { printf("(%f,%f)\n",a->real,a->imag); } ( , ) ( , ) Autumn 2016 Programming and Data Structure
12
Programming and Data Structure
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. The operator “–>” enjoys the highest priority among operators. ++ptr –> roll will increment roll, not ptr. (++ptr) –> roll will do the intended thing. Autumn 2016 Programming and Data Structure
13
Structures and Functions
A structure can be passed as argument to a function. A function can also return a structure. The process shall be illustrated with the help of an example. A function to add two complex numbers. Autumn 2016 Programming and Data Structure
14
Example: complex number addition
#include <stdio.h> struct complex { float re; float im; }; main() { struct complex a, b, c; scanf (“%f %f”, &a.re, &a.im); scanf (“%f %f”, &b.re, &b.im); c = add (a, b) ; printf (“\n %f %f”, c.re, c.im); } struct complex add (x, y) struct complex x, y; { struct complex t; t.re = x.re + y.re ; t.im = x.im + y.im ; return (t) ; } Autumn 2016 Programming and Data Structure
15
Example: Alternative way using pointers
#include <stdio.h> struct complex { float re; float im; }; main() { struct complex a, b, c; scanf (“%f %f”, &a.re, &a.im); scanf (“%f %f”, &b.re, &b.im); add (&a, &b, &c) ; printf (“\n %f %f”, c,re, c.im); } void add (x, y, t) struct complex *x, *y, *t; { t->re = x->re + y->re ; t->im = x->im + y->im ; } Autumn 2016 Programming and Data Structure
16
Dynamic Memory Allocation
Autumn 2016 Programming and Data Structure
17
Programming and Data Structure
Basic Idea Many a time we face situations where data is dynamic in nature. Amount of data cannot be predicted beforehand. Number of data item keeps changing during program execution. Such situations can be handled more easily and effectively using dynamic memory management techniques. Autumn 2016 Programming and Data Structure
18
Programming and Data Structure
Contd. C language requires the number of elements in an array to be specified at compile time. Often leads to wastage or memory space or program failure. Dynamic Memory Allocation Memory space required can be specified at the time of execution. C supports allocating and freeing memory dynamically using library routines. Autumn 2016 Programming and Data Structure
19
Memory Allocation Process in C
Local variables Stack Free memory Heap Global variables Permanent storage area Instructions Autumn 2016 Programming and Data Structure
20
Programming and Data Structure
Contd. The program instructions and the global variables are stored in a region known as permanent storage area. The local variables are stored in another area called stack. 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 Autumn 2016 Programming and Data Structure
21
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. Autumn 2016 Programming and Data Structure
22
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 assigned to any pointer type. General format: ptr = (type *) malloc (byte_size) ; Autumn 2016 Programming and Data Structure
23
Programming and Data Structure
Contd. 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. p 400 bytes of space Autumn 2016 Programming and Data Structure
24
Programming and Data Structure
Contd. cptr = (char *) malloc (20) ; Allocates 10 bytes of space for the pointer cptr of type char. sptr = (struct stud *) malloc (10 * sizeof (struct stud)); Autumn 2016 Programming and Data Structure
25
Programming and Data Structure
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. Autumn 2016 Programming and Data Structure
26
Programming and Data Structure
Example #include <stdio.h> main() { int i,N; float *height; float sum=0,avg; printf("Input the number of students. \n"); scanf("%d",&N); height=(float *) malloc(N * sizeof(float)); printf("Input heights for %d students \n",N); for(i=0;i<N;i++) scanf("%f",&height[i]); sum+=height[i]; avg=sum/(float) N; printf("Average height= %f \n", avg); } Input the number of students. 5 Input heights for 5 students Average height= Autumn 2016 Programming and Data Structure
27
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 format: free (ptr) ; where ptr is a pointer to a memory block which has been already created using malloc. Autumn 2016 Programming and Data Structure
28
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. If the original allocation is done by the statement ptr = malloc (size) ; then reallocation of space may be done as ptr = realloc (ptr, newsize) ; Autumn 2016 Programming and Data Structure
29
Programming and Data Structure
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. The function guarantees that the old data remains intact. If it is unable to allocate, it returns NULL and frees the original block. Autumn 2016 Programming and Data Structure
30
Revisiting strings and arrays…
Autumn 2016 Programming and Data Structure
31
Programming and Data Structure
Introduction A string is an array of characters. Individual characters are stored in memory in ASCII code. A string is represented as a sequence of characters terminated by the null (‘\0’) character. “Hello” ‘\0’ l e H o Autumn 2016 Programming and Data Structure
32
Declaring String Variables
A string is declared like any other array: char string-name [size]; size determines the number of characters in string_name. When a character string is assigned to a character array, it automatically appends the null character (‘\0’) at the end of the string. size should be equal to the number of characters in the string plus one. Autumn 2016 Programming and Data Structure
33
Programming and Data Structure
Examples char name[30]; char city[15]; char dob[11]; A string may be initialized at the time of declaration. char city[15] = “Calcutta”; char city[15] = {‘C’, ‘a’, ‘l’, ‘c’, ‘u’, ‘t’, ‘t’, ‘a’}; char dob[] = “ ”; Equivalent Autumn 2016 Programming and Data Structure
34
Reading Strings from the Keyboard
Two different cases will be considered: Reading words Reading an entire line Autumn 2016 Programming and Data Structure
35
Programming and Data Structure
Reading “words” scanf can be used with the “%s” format specification. char name[30]; : scanf (“%s”, name); The ampersand (&) is not required before the variable name with “%s”. The problem here is that the string is taken to be upto the first white space (blank, tab, carriage return, etc.) If we type “Rupak Biswas” name will be assigned the string “Rupak” Autumn 2016 Programming and Data Structure
36
Reading a “line of text”
In many applications, we need to read in an entire line of text (including blank spaces). We can use the getchar() function for the purpose. Autumn 2016 Programming and Data Structure
37
Programming and Data Structure
char line[81], ch; int c=0; : do { ch = getchar(); line[c] = ch; c++; } while (ch != ‘\n’); c = c – 1; line[c] = ‘\0’; Read characters until CR (‘\n’) is encountered Make it a valid string Autumn 2016 Programming and Data Structure
38
Reading a line :: Alternate Approach
char line[81]; : scanf (“%[ ABCDEFGHIJKLMNOPQRSTUVWXYZ]”, line); Reads a string containing uppercase characters and blank spaces char line[81]; : scanf (“%[^\n]”, line); Reads a string containing any characters Autumn 2016 Programming and Data Structure
39
Writing Strings to the Screen
We can use printf with the “%s” format specification. char name[50]; : printf (“\n %s”, name); Autumn 2016 Programming and Data Structure
40
Processing Character Strings
There exists a set of C library functions for character string manipulation. strcpy :: string copy strlen :: string length strcmp :: string comparison strtcat :: string concatenation It is required to include the following #include <string.h> Autumn 2016 Programming and Data Structure
41
Programming and Data Structure
strcpy() Works very much like a string assignment operator. strcpy (string1, string2); Assigns the contents of string2 to string1. Examples: strcpy (city, “Calcutta”); strcpy (city, mycity); Warning: Assignment operator do not work for strings. city = “Calcutta”; INVALID Autumn 2016 Programming and Data Structure
42
Programming and Data Structure
strlen() Counts and returns the number of characters in a string. len = strlen (string); /* Returns an integer */ The null character (‘\0’) at the end is not counted. Counting ends at the first null character. Autumn 2016 Programming and Data Structure
43
Programming and Data Structure
char city[15]; int n; : strcpy (city, “Calcutta”); n = strlen (city); n is assigned 8 Autumn 2016 Programming and Data Structure
44
Programming and Data Structure
strcmp() Compares two character strings. int strcmp (string1, string2); Compares the two strings and returns 0 if they are identical; non-zero otherwise. Examples: if (strcmp (city, “Delhi”) = = 0) { ……. } if (strcmp (city1, city2) ! = 0) { ……. } Autumn 2016 Programming and Data Structure
45
Programming and Data Structure
strcat() Joins or concatenates two strings together. strcat (string1, string2); string2 is appended to the end of string1. The null character at the end of string1 is removed, and string2 is joined at that point. Example: strcpy (name1, “Amit “); strcpy (name2, “Roy“); strcat (name1, name2); ‘\0’ i m A t ‘\0’ y o R i m A t ‘\0’ y o R Autumn 2016 Programming and Data Structure
46
Include header for string processing Character Array for String
/* Read a line of text and count the number of uppercase letters */ #include <stdio.h> #include <string.h> main() { char line[81]; int i, n, count=0; printf(“Input the line \n”); scanf (“%[^\n]”, line); n = strlen (line); for (i=0; i<n; i++) if (isupper (line[i])) count++; } printf (“\n The number of uppercase letters in the string %s is %d”, line, count); Example Include header for string processing Character Array for String Reading a line of text Computing string length Checking whether a character is Uppercase Autumn 2016 Programming and Data Structure
47
Two Dimensional Arrays
We have seen that an array variable can store a list of values. Many applications require us to store a table of values. Subject 1 Subject 2 Subject 3 Subject 4 Subject 5 75 82 90 65 76 68 80 70 72 88 74 85 50 40 Student 1 Student 2 Student 3 Student 4 Autumn 2016 Programming and Data Structure
48
Programming and Data Structure
Contd. The table contains a total of 20 values, five in each line. The table can be regarded as a matrix consisting of four rows and five columns. C allows us to define such tables of items by using two-dimensional arrays. Autumn 2016 Programming and Data Structure
49
Programming and Data Structure
Declaring 2-D Arrays General form: type array_name [row_size][column_size]; Examples: int marks[4][5]; float sales[12][25]; double matrix[100][100]; Autumn 2016 Programming and Data Structure
50
Accessing Elements of a 2-D Array
Similar to that for 1-D array, but use two indices. First indicates row, second indicates column. Both the indices should be expressions which evaluate to integer values. Examples: x[m][n] = 0; c[i][k] += a[i][j] * b[j][k]; a = sqrt (a[j*3][k]); Autumn 2016 Programming and Data Structure
51
How is a 2-D array is stored in memory?
Starting from a given memory location, the elements are stored row-wise in consecutive memory locations. x: starting address of the array in memory c: number of columns k: number of bytes allocated per array element a[i][j] is allocated memory location at address x + (i * c + j) * k a[0]0] a[0][1] a[0]2] a[0][3] a[1][0] a[1][1] a[1][2] a[1][3] a[2][0] a[2][1] a[2][2] a[2][3] Row 0 Row 1 Row 2 Autumn 2016 Programming and Data Structure
52
How to read the elements of a 2-D array?
By reading them one element at a time for (i=0; i<nrow; i++) for (j=0; j<ncol; j++) scanf (“%f”, &a[i][j]); The ampersand (&) is necessary. The elements can be entered all in one line or in different lines. Autumn 2016 Programming and Data Structure
53
How to print the elements of a 2-D array?
By printing them one element at a time. for (i=0; i<nrow; i++) for (j=0; j<ncol; j++) printf (“\n %f”, a[i][j]); The elements are printed one per line. printf (“%f”, a[i][j]); The elements are all printed on the same line. Autumn 2016 Programming and Data Structure
54
Programming and Data Structure
Contd. for (i=0; i<nrow; i++) { printf (“\n”); for (j=0; j<ncol; j++) printf (“%f ”, a[i][j]); } The elements are printed nicely in matrix form. How to print two matrices side by side? Autumn 2016 Programming and Data Structure
55
Example: Matrix Addition
#include <stdio.h> main() { int a[100][100], b[100][100], c[100][100], p, q, m, n; scanf (“%d %d”, &m, &n); for (p=0; p<m; p++) for (q=0; q<n; q++) scanf (“%d”, &a[p][q]); scanf (“%d”, &b[p][q]); for (p=0; p<m; p++) for (q=0; q<n; q++) c[p]q] = a[p][q] + b[p][q]; { printf (“\n”); printf (“%f ”, a[p][q]); } Autumn 2016 Programming and Data Structure
56
Passing Arrays to a Function
An array name can be used as an argument to a function. Permits the entire array to be passed to the function. Array name is passed as the parameter, which is effectively the address of the first element. Rules: The array name must appear by itself as argument, without brackets or subscripts. The corresponding formal argument is written in the same manner. Declared by writing the array name with a pair of empty brackets. Dimension or required number of elements to be passed as a separate parameter. Autumn 2016 Programming and Data Structure
57
Programming and Data Structure
The Actual Mechanism When an array is passed to a function, the values of the array elements are not passed to the function. The array name is interpreted as the address of the first array element. The formal argument therefore becomes a pointer to the first array element. When an array element is accessed inside the function, the address is calculated using the formula stated before. Changes made inside the function are thus also reflected in the calling program. Autumn 2016 Programming and Data Structure
58
Programming and Data Structure
Contd. Passing parameters in this way is called call-by-reference. Normally parameters are passed in C using call-by-value. Basically what it means? If a function changes the values of array elements, then these changes will be made to the original array that is passed to the function. This does not apply when an individual element is passed on as argument. Autumn 2016 Programming and Data Structure
59
Programming and Data Structure
Passing 2-D Arrays Similar to that for 1-D arrays. The array contents are not copied into the function. Rather, the address of the first element is passed. For calculating the address of an element in a 2-D array, we need: The starting address of the array in memory. Number of bytes per element. Number of columns in the array. The above three pieces of information must be known to the function. Autumn 2016 Programming and Data Structure
60
Programming and Data Structure
Example Usage #include <stdio.h> main() { int a[15][25], b[15]25]; : add (a, b, 15, 25); } void add (int x[][25], y[][25], int rows, int cols) { : } We can also write int x[15][25], y[15][25]; Number of columns Autumn 2016 Programming and Data Structure
61
Example: Transpose of a matrix
void transpose (int x[][100], int n) { int p, q; for (p=0; p<n; p++) for (q=0; q<n; q++) t = x[p][q]; x[p][q] = x[q][p]; x[q][p] = t; } a[100][100] transpose(a,3) Autumn 2016 Programming and Data Structure
62
Programming and Data Structure
The Correct Version void transpose (int x[][100], n) { int p, q; for (p=0; p<n; p++) for (q=p; q<n; q++) t = x[p][q]; x[p][q] = x[q][p]; x[q][p] = t; } Autumn 2016 Programming and Data Structure
63
Some Exercise Problems to Try Out
Multiply two matrices of orders m x n and n x p respectively. Autumn 2016 Programming and Data Structure
64
Dynamic Allocation of 2-D Arrays
Autumn 2016 Programming and Data Structure
65
Programming and Data Structure
Pointer to Pointer Example: int **p; p=(int **) malloc(3 * sizeof(int *)); p[0] p int ** int * p[1] int * int * p[2] Autumn 2016 Programming and Data Structure
66
Programming and Data Structure
2-D Array Allocation #include <stdio.h> #include <stdlib.h> int **allocate(int h, int w) { int **p; int i,j; p=(int **) calloc(h, sizeof (int *) ); for(i=0;i<h;i++) p[i]=(int *) calloc(w,sizeof (int)); return(p); } void read_data(int **p,int h,int w) { int i,j; for(i=0;i<h;i++) for(j=0;j<w;j++) scanf ("%d",&p[i][j]); } Allocate array of pointers Elements accessed like 2-D array elements. Allocate array of integers for each row Autumn 2016 Programming and Data Structure
67
Programming and Data Structure
2-D Array: Contd. void print_data(int **p,int h,int w) { int i,j; for(i=0;i<h;i++) for(j=0;j<w;j++) printf("%5d ",p[i][j]); printf("\n"); } main() { int **p; int M,N; printf("Give M and N \n"); scanf("%d%d",&M,&N); p=allocate(M,N); read_data(p,M,N); printf("\n The array read as \n"); print_data(p,M,N); } Give M and N 3 3 1 2 3 4 5 6 7 8 9 The array read as Autumn 2016 Programming and Data Structure
68
Linked List :: Basic Concepts
A list refers to a set of items organized sequentially. An array is an example of a list. The array index is used for accessing and manipulation of array elements. Problems with array: The array size has to be specified at the beginning. Deleting an element or inserting an element may require shifting of elements. Autumn 2016 Programming and Data Structure
69
Programming and Data Structure
Contd. A completely different way to represent a list: Make each item in the list part of a structure. The structure also contains a pointer or link to the structure containing the next item. This type of list is called a linked list. Structure 1 item Structure 2 item Structure 3 item Autumn 2016 Programming and Data Structure
70
Programming and Data Structure
Contd. Each structure of the list is called a node, and consists of two fields: One containing the item. The other containing the address of the next item in the list. The data items comprising a linked list need not be contiguous in memory. They are ordered by logical links that are stored as part of the data in the structure itself. The link is a pointer to another structure of the same type. Autumn 2016 Programming and Data Structure
71
Programming and Data Structure
Contd. Such a structure can be represented as: struct node { int item; struct node *next; } ; Such structures which contain a member field pointing to the same structure type are called self-referential structures. node item next Autumn 2016 Programming and Data Structure
72
Programming and Data Structure
Contd. In general, a node may be represented as follows: struct node_name { type member1; type member2; ……… struct node_name *next; }; Autumn 2016 Programming and Data Structure
73
Programming and Data Structure
Illustration Consider the structure: struct stud { int roll; char name[30]; int age; struct stud *next; }; Also assume that the list consists of three nodes n1, n2 and n3. struct stud n1, n2, n3; Autumn 2016 Programming and Data Structure
74
Programming and Data Structure
Contd. To create the links between nodes, we can write: n1.next = &n2 ; n2.next = &n3 ; n3.next = NULL ; /* No more nodes follow */ Now the list looks like: roll name age next n3 n2 n1 Autumn 2016 Programming and Data Structure
75
Programming and Data Structure
Example #include <stdio.h> struct stud { int roll; char name[30]; int age; struct stud *next; }; main() struct stud n1, n2, n3; struct stud *p; scanf (“%d %s %d”, &n1.roll, n1.name, &n1.age); scanf (“%d %s %d”, &n2.roll, n2.name, &n2.age); scanf (“%d %s %d”, &n3.roll, n3.name, &n3.age); n1.next = &n2 ; n2.next = &n3 ; n3.next = NULL ; /* Now traverse the list and print the elements */ p = n1 ; /* point to 1st element */ while (p != NULL) { printf (“\n %d %s %d”, p->roll, p->name, p->age); p = p->next; } Autumn 2016 Programming and Data Structure
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.