14/10/17
Lexicographic (Dictionary) Ordering
• Badri < Devendra
• Janak < Janaki
CS1100 • Shiva < Shivendra
• Seeta < Sita
Introduction to Programming
Sorting Strings and Pointers • Based on the ordering of characters
Madhu Mutyam
• A< B…<Y<Z< a< b<c<...< y < z
Department of Computer Science and Engineering
Indian Institute of Technology Madras
upper case before lower case
Course Material – SD, SB, PSK, NSN, DK, TAG – CS&E, IIT M 1 2
SD, PSK, NSN, DK, TAG – CS&E, IIT M
Lexicographic Ordering Lexicographic Ordering
• What about blanks? • What if two names are identical?
– “Bill Clinton” < “Bill Gates” • There is a danger that the character arrays may
– “Ram Subramanian” < “Ram Subramanium” contain some unknown values beyond ‘\0’
– “Ram Subramanian” < “Rama Awasthi” • Solutions
• In ASCII the blank (code = 32) comes before all – One could begin by initializing the arrays to blanks
other characters. The above cases are taken care before we begin.
of automatically. – One could explicitly look for the null character ‘\0’
• Exercise: Look up ASCII codes on the web. – When the two names are equal it may not matter if
either one is reported before the other. Though in
stable sorting there is a requirement that equal
elements should remain in the original order.
SD, PSK, NSN, DK, TAG – CS&E, IIT M 3 SD, PSK, NSN, DK, TAG – CS&E, IIT M 4
Comparing Strings (char Arrays) Built-in String Comparison
Pointers - address of char array
• Given two strings A[i][] and A[j][] of length n, • #include <string.h> – we will look at them later
return the index of the string that comes earlier in • int strcmp(const char *s1, const char *s2);
the lexicographic order • int strncmp(const char *s1, const char *s2, size_t n);
int strCompare(char A[ ][MAX_SIZE], int i, int j, int • int strcmp(char*, char*) – compares two strings (char
MAX_SIZE){ arrays)
Skip common characters if any
int k=0; • The return values are:
while ((A[i][k] == A[j][k]) && k<MAX_SIZE) k++;
if (A[i][k] == ‘\0’) return i; • 0 – If both strings are equal
if (A[j][k] == ‘\0’) return j; If one string is prefix • 1 – If first string is lexicographically greater than second
if (A[i][k] < A[j][k]) return i; of the other return that • -1 – If second string is lexicographically greater than first
else return j;
}
SD, PSK, NSN, DK, TAG – CS&E, IIT M 5 SD, PSK, NSN, DK, TAG – CS&E, IIT M 6
1
14/10/17
Other Built-in String Functions ArrayCopy
• char* strcat(char* dest, char* src) Copies content of ith row of array into the jth row
– Strcat combines two strings and returns a pointer to
the destination string. In order for this function to array[i][……]
work (and not seg fault), you must have enough room
in the destination for both strings.
array[j][……]
• char* strcpy(char* dest, char* src)
– Strcpy copies one string to another. The destination void arrayCopy (char array[ ][MAX_SIZE], int i, int j,
must be large enough to accept the contents of the int MAX_SIZE) {
source string. int k;
for (k =0; k < MAX_SIZE; k++)
• int strlen(const char* s) array[j][k] = array[i][k];
– Strlen returns the length of a string, excluding ‘\0’ }
SD, PSK, NSN, DK, TAG – CS&E, IIT M 7 SD, PSK, NSN, DK, TAG – CS&E, IIT M 8
ArraySwap Sorting String Arrays
array[i][……] • Modify InsertionSort to sort array names[ ] of
names
array[j][……] • Use strCompare to compare names
• Use arrayCopy to move names
void arraySwap (char array[ ][MAX_SIZE], int i, int j,
int MAX_SIZE){
• In the exercise where names[ ] and marks[ ] have
for (k =0; k < MAX_SIZE; k++) to be sorted in concert, modify the sorting
swap(array, i, j, k); algorithm to Compact structures to hold
– compare in one array both to be explored later
}
• names[ ] for alphabetic order
Note: We exchange the entire arrays. If we knew the length of
the longer string, we could have a different end condition. • marks[ ] for decreasing marks order
SD, PSK, NSN, DK, TAG – CS&E, IIT M 9 – move elements of both
SD, PSK, NSN, DK, TAG – CS&E, IIT M 10
Printing a Reversed String Palindromes
• Strings/sequences that read the same left to right
main( ) { or right to left
int i = 4;
• string == reversed string
char c;
– malayalam
do{
– god live evil dog
c = "hello"[i];
– able was I ere I saw elba
printf("%c",c);
i --; – don’t nod
}while(i >= 0); – never odd or even
printf("\n"); • notice that we ignore blanks (4, 5) and other
} characters (4)
SD, PSK, NSN, DK, TAG – CS&E, IIT M 11
– preprocess the string to remove them
SD, PSK, NSN, DK, TAG – CS&E, IIT M 12
2
14/10/17
Reversing an Array Limits for Iteration
• Swap the first element with last S N A K E
for (i=0; i<n; i++)
reverse
– a(0) with a(n – 1) swap (a, int i, int n–1–i);
i=0 E N A K S
• second with second last
– a(1) with a(n – 2) i=1 E K A N S Job done!
• … a(i) with a((n – 1) – i) Stop at halfway mark!
i=2 E K A N S for(i=0; i<n/2; i++)
• How about the following code?
void swap (char a[ ], int i, int j){ void swap (char a[ ], int i, int j){
for (i=0; i<n; i++) char c; i=3 E N A K S
char c;
swap (a, i, n-1-i); c = a[i]; c = a[i];
a[i]=a[j]; i=4 S N A K E a[i]=a[j];
a[j]=c; a[j]=c;
13 14
SD, PSK, NSN, DK, TAG – CS&E, IIT M
} SD, PSK, NSN, DK, TAG – CS&E, IIT M
}
Exercise Palindrome Squares
• Compute the transpose of a matrix • Write a program to check if a square matrix
• Compute in place transpose of a square matrix contains a palindrome table.
• Two examples are given below
from http://www.fun-with-words.com/palin_example.html
T A B L E T A S
A C E D O A C T S T E P R A T S
S T E E P B E E T I M E A B U T
L D E E M I T T U B A
E O P P E T S S T A R
SD, PSK, NSN, DK, TAG – CS&E, IIT M 15 SD, PSK, NSN, DK, TAG – CS&E, IIT M 16
Concatenating Two Strings Concatenating Two Strings
S t r i n g i n C \0 . . . S t r i n g i n C \0 . . .
A n o t h e r s t r i n g i n C \0 . . . A n o t h e r s t r i n g i n C \0 . . .
/* Arrays of strings */ /* Check that we have enough space for both strings */
#include <stdio.h> if (sizeof str[0] < count1 + count2 + 1)
void main() { printf("\n Not enough space for both strings.");
char str[ ][40] = {"String in C”, "Another string in C”}; else { /* Copy 2nd string to first */
int i = count1, j = 0;
int count1 = 0; /* Length of first string */ while((str[0][i++] = str[1][j++]) != '\0');
int count2 = 0; /* Length of second string */ printf("\n%s", str[0]); /* Output combined string */
/* find the length of the strings */ }
while (str[0][count1] != '\0') count1++; /* 11 */ }
while (str[1][count2] != '\0') count2++; /* 19 */
SD, PSK, NSN, DK, TAG – CS&E, IIT M 17 SD, PSK, NSN, DK, TAG – CS&E, IIT M 18
3
14/10/17
What is a Pointer? l-value and r-value
• Recap: a variable int k Addr • Given a variable k
– Names a memory location that can k 38 100 – Its l-value refers to the address of the memory location
hold one value at a time – l-value is used on the left side of an assignment
– Memory is allocated statically at *p • Ex. k = expression
compile time – Its r-value refers to the value stored in the memory
– One name ⇔ one value location
• A pointer variable int *p p 250
100 200 – r-value is used in the right hand side of an assignment
– Contains the address of a memory • Ex. var = k + …
*p
location that contains the actual value • Pointers allow one to manipulate the l-value!
m 84 250
– Memory can be allocated at runtime
– One name ⇔ many values
SD, PSK, NSN, DK, TAG – CS&E, IIT M 19 SD, PSK, NSN, DK, TAG – CS&E, IIT M 20
Pointer Variables Declaring Pointers
• Pointer variables are variables that store the • Pointer variable – precede its name with an
address of a memory location asterisk
• Memory required by a pointer variable depends • Pointer type - the type of data stored at the
upon the size of the memory in the machine address
– one byte could address a memory of 256 locations – For example, int *p;
– two bytes can address a memory of 64K locations – p is the name of the variable. The ‘*’ informs the
– four bytes can address a memory of 4G locations compiler that p is a pointer variable
– modern machines have RAM of 1GB or more… – The int says that p is used to point to an integer
value
• The task of allocating this memory is best left to
Ted Jenson’s tutorial on pointers
the system http://pweb.netcom.com/~tjensen/ptr/cpoint.htm
SD, PSK, NSN, DK, TAG – CS&E, IIT M 21 SD, PSK, NSN, DK, TAG – CS&E, IIT M 22
Contents of Pointer Variables Dereferencing Operator
• In ANSI C, if a pointer is declared outside any • The asterisk symbol is the "dereferencing
function, it is initialized to a null pointer operator" and it is used as follows
– For example, *ptr = 7;
int k; – Will copy 7 to the address pointed to by ptr
int *p; – Thus if ptr "points to" (contains the address of) k, the
p = &k; //assigns the address of int k to p above statement will set the value of k to 7
if (p == NULL) //tests for a null pointer
• Using '*' is a way of referring to the value in
p = malloc(sizeof(int)); //dynamic allocation,
the location which ptr is pointing to, but not the
//creates an anonymous int
// in memory at runtime value of the pointer itself
– printf("%d\n",*ptr); --- prints the number 7
SD, PSK, NSN, DK, TAG – CS&E, IIT M 23 SD, PSK, NSN, DK, TAG – CS&E, IIT M 24
4
14/10/17
short int Pointer Pointer Arithmetic
• short *ptr; ptr
– says that ptr is the address of a short integer type
• short – allocates two bytes of memory
ptr • ptr = ptr +1;
– says to point to the next data item after this one
100 101 102 103 104 105 …
ptr
– *ptr = 20; //store the value 20 in the above two bytes
• if we had said “int *ptr”
– it would have allocated 4 bytes of memory Makes sense only for same type data – eg. an array of integers
SD, PSK, NSN, DK, TAG – CS&E, IIT M 25 SD, PSK, NSN, DK, TAG – CS&E, IIT M 26
Memory Needed for a Pointer
• A pointer requires two chunks of memory to be
allocated:
– Memory to hold the pointer (address)
• Allocated statically by the pointer declaration
– Memory to hold the value pointed to
• Allocated statically by a variable declaration
• OR allocated dynamically by malloc( )
• One variable or pointer declaration à allocation
of one chunk of memory
SD, PSK, NSN, DK, TAG – CS&E, IIT M 27