0% found this document useful (0 votes)
94 views67 pages

Computer Programming (CS F111) Strings and Dynamic Memory: BITS Pilani

The document provides an overview of strings and dynamic memory in C programming. It discusses initializing and manipulating strings using built-in functions like strlen(), strcat(), strcpy(), and strcmp(). It also touches on reading and writing strings, common mistakes, and substring searching. The document is intended to cover important concepts for placements and provide exposure to dynamic memory at a basic level.

Uploaded by

SOUBHIK ROY
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
94 views67 pages

Computer Programming (CS F111) Strings and Dynamic Memory: BITS Pilani

The document provides an overview of strings and dynamic memory in C programming. It discusses initializing and manipulating strings using built-in functions like strlen(), strcat(), strcpy(), and strcmp(). It also touches on reading and writing strings, common mistakes, and substring searching. The document is intended to cover important concepts for placements and provide exposure to dynamic memory at a basic level.

Uploaded by

SOUBHIK ROY
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

Computer Programming

(CS F111)
Strings and Dynamic memory
BITS Pilani Dr. Lov Kumar, Dr. Sudeepta Mishra, Mr. Abhishek Thakur
Hyderabad Campus
Department of CSIS
Note:
1. Some parts are important from placements perspective as
multiple questions are asked on Strings.
2. Dynamic memory is more from the perspective of handling
structures and linked list – at exposure level only.

2 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


Spot the errors / warnings
1. int my_array[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
2. int my_array[2][3] = { 1, 2, 3, 4, 5, 6 };
3. int arr[2][]= { { 1, 2, 3 }, { 4, 5, 6 } };
4. int arr[][] = { { 1, 2, 3 }, { 4, 5, 6 } };
5. int someFunc(int i) {
6. int i=2;
7. int 4x=i*4;
8. return 5*i;
9. }

https://www.polleverywhere.com/clickable_images/vyAuUprs0F9z2Vj
3 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus
CS F111 Second Semester 2011-12
Strings

• String is a sequence of characters


• Contains a special character ‘\0’ (NULL)
• ‘\0’ marks the end of string.

Ex1 : "India is Great" is a string


Ex2 : "The result is: %d\n" in printf("The result is: %d\n",
result);
• string is represented in C as an array of type char
• Declaration of strings:
• char str[30];
• char line[80];

5 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


Initialization

char str1[17] = {'C', 'o', 'm', 'p', 'u', 't', 'e', 'r' , ' ' , 'P', 'r', 'o', 'g', 'r', 'a', 'm' , '\0'};

char str2[17] = "Computer Program"; //with size


char str3[]= "Computer Program"; //without size

char name[ ] = “BITS PILANI”;

char name[15] = “BITS PILANI”;

B I T S P I L A N I \0 \0 \0 \0

6 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


String Initialization

char str[9] = “I like C”;


same as
char str[9]={‘I’,‘ ‘,’l’,‘i’,’k’,’e’,‘ ‘,’C’,’\0’};

Q. Is there any difference between following Initialization?


char str[]=“BITS”;
char str[4]= “BITS”;

Ans: Yes, in second declaration there is no null character

7 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


Read & Display String

char name [30];


scanf (“%s”, name ); /* there is no “&” before the string
variable name */

Note : Reading will stop as soon as the first whitespace


character (blank, tab, return) is encountered.

printf (“%s”, name );

Note : A string is printed up to the NULL(‘\0’) character.

8 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


Display String : Character by
Character
Idea : You can display character unless you
encounter ‘\0’ character

9 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


Reading a String : Using scanf()

char text[30];
printf(“Enter a string: ”);
scanf(“%s”,text);
printf(“The string is : %s”,text);
Sample output:
Enter a string: hello
The string is: hello
Enter a string: hello how are you
The string is: hello
Note: scanf() takes string without blank space by default
10 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus
Reading a String of specific
kind

• Read string only containing alphabets a-z


• Use format specifier : %[a-z]s
• The moment it encounters any character apart from a-z, it will stop
scanning further characters.

• Read string only containing a,b,c,d


• Use format specifier : %[abcd]s
• The moment it encounters any character apart from a,b,c,d, it will stop
scanning further characters.

• Read a string until newline


• Use format specifier : %[^\n]s
• The moment it encounters newline, it will stop scanning further characters.

11 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


Reading a String : Containing only alphabets

char text[30];
printf(“Enter a string: ”);
scanf(“%[a-z]s”,text);
printf(“The string is : %s”,text);

Sample output:
Enter a string: hello
The string is: hello
Enter a string: hello123pla
The string is: hello
12 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus
Reading a String : containing only a, b,
c, d

char text[30];
printf(“Enter a string: ”);
scanf(“%[abcd]s”,text);
printf(“The string is : %s”,text);

Sample output:
Enter a string: abbcddsence
The string is: abbcdd

13 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


Reading a String : till newline

char name[20];
printf(“Enter your name: ”);
scanf(“%[^\n]s”,name);
printf(“The string is : %s\n”,name);

Sample output:
Enter a string: hello
The string is: hello
Enter a string: BITS PILANI
The string is: BITS PILANI
14 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus
Reading a String : till newline

• fgets() : It accepts 3 parameters array, max_size,


input stream (here it’s : stdin since we want to read
input from keyboard)

char str[100];
fgets(str, 100, stdin);

Note : it reads 99 characters, white space is also


counted as a characters
Even if you enter more than 99 characters, only the
first 99 are taken.

15 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


Writing a String : fputs

• fputs() : print to output stream

fputs(str, stdout);

16 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


More I/O functions

• gets()
• puts()
• unsafe library functions – specially gets – use fgets instead
• can take more no. of characters as input than the
size of the character array
• results in abnormal program behavior/termination

17 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


Printing a string

char str[30]={'a','b','\0','c','d'};
printf("\n%s",str);  prints only ab

printf("\n%c",'\0');  no character is printed on console

18 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


Common Mistakes

• char name[10] = “BITS PILANI” Not sufficient space

• char name[ ]; Array size missing

• char
name [12];
name = “BITS PILANI”; Incompatible types in
assignment
• charstr1[6] = “Hello”;
char str2[6];
str2 = str1; Name of string is a pointer
const that cannot be used
as a lvalue

19 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


String Library
Header file : string.h

Important Library functions:

• strlen(str)
• strcat(str1, str2) safe option strncat()
char *strncat(char *dest, const char *src, size_t n);

• strcpy(str1, str2) safe option strncpy()


char *strncpy(char *dest, const char *src, size_t n);

• strcmp(str1, str2) or strncmp() and strncmpi()

20 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


strlen(str)

• returns the size as long int


• does not count ‘\0’
• counts whitespaces

21 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


strcat(str1, str2)

• appends name2 to the end of the name1


• name1 should be large enough

22 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


strcpy(str1, str2)

• name2 is copied into name1


• if name1 contains any previous string, it is overwritten
• name2 should be large enough

23 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


strcpy(str1, str2)

int main()
{
char name1[15] = "ooooooooo";
char name2[8] = "pppppp";
strcpy(name1, name2);
printf("%s\n",name1);

OUTPUT:
pppppp

24 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


strcpy(str1, str2)

#include<stdio.h>
#include<string.h>

int main()
{
char name1[15] = "abcd";
char name2[8] = "xyzw";
strcat(name1,strcpy(name1, name2));
printf("%s\n",name1);

OUTPUT:
xyzwxyzw

25 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


strcmp(str1, str2)

26 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


Substring search
Exposure only
char *strstr(const char *haystack, const char *needle);

char *strcasestr(const char *haystack, const char *needle);

27 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


Few outputs
#include<stdio.h>
#include<string.h>

int main()
{
char name1[15]="abcefgh";
char name2[]="xyz";
char name3[]="efg";
strcpy(name1,name2);
printf("\n%s\n%c",name1,name1[5]);
}

Output---
xyz
g

28 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


Few outputs

#include<stdio.h>
#include<string.h>

int main()
{
char name1[15]="abcefgh";
char name2[]="xyz";

printf(“\n %d”,strcmp(name1,name2));
}

Output ---
-23 //(name1 - name2)

29 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


Variants to compare strings

• strncmp(str1, str2, n)
• compares at most the first n characters of str1 and str2

• strcmpi(str1, str2)
• compares str1 and str2 by ignoring case

• strncmpi(str1, str2, n)
• compares at most the first n characters of str1 and str2 by
ignoring case

30 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


How to pass string in a function ?

• You need to mention only one argument which is sufficient


to represent your string.
• Optional to pass length as special property of string is that it
has NULL character at the end (unless updating the array to
larger size).
return-type functionName(char str[]);
or
return-type functionName(char str[], int len);

• Use character array name while calling the function


functionName(str); or functionName(str, len);

31 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


Arrays in function

data-type fnName(char *str);


fnName(str); // function Call

CS F111 BITS Pilani, Hyderabad Campus


String constant as a Pointer

• Text enclosed in double quote characters (such as "example") is a string


constant
• Produces a block of storage whose type is array of char, and whose value is
the sequence of characters between the double quotes, with a null character
(ASCII code 0) automatically added at the end
• All the escape sequences for character constants work here too.

• Sometimes string constant behaves as a pointer

Example 1: char *pmessage = “now is the time”;

CS F111 BITS Pilani, Hyderabad Campus


What’s the Difference ???

CS F111 BITS Pilani, Hyderabad Campus


Predict Output

Output : YES Output : NO


Explanation: msg1 and Explanation : msg1 and
msg2 will point to string msg2 are array hence are
literal “Hello World” allocated separate space.
So they are unequal , will
give warning (Remember :
array name is pointer )

CS F111 BITS Pilani, Hyderabad Campus


Array of pointers
Exposure only

• How to declare it :
data-type *arrayName[SIZE];

• Each cell can store address

CS F111 BITS Pilani, Hyderabad Campus


Array of pointers
Exposure only

CS F111 BITS Pilani, Hyderabad Campus


Array of Pointers
Example usage

int main()
{
char *month[] = {"January", "February", "March", "April",
"May", "June", "July", "August" };
int i, j;
for(i = 0; i < 5; i++)
printf("\n%s",month[i]);
for(i = 0; i < 5; i++)
for(j = 0; month[i][j] != '\0'; j++)
printf("\n%c", month[i][j]);
return 0;
}

CS F111 BITS Pilani, Hyderabad Campus


Command line Argument in main()
Exposure ONLY

• We can pass command line argument when we execute


our program $ ./a.out arg1 arg2 arg3

• We have main() accepting 2 argument argc and argv


• argc : number of command line argument.
• argv : is a pointer to an array of character strings that contain the
argument, one per string . Note: argv[0] is the exectutable name

CS F111 BITS Pilani, Hyderabad Campus


Command line Argument in main()
Exposure ONLY

• ./a.out > log  only 1 command line argument

• int main(float argc, char *argv[])  gives warning

• int main(int argc, char *argv[], float a)  might generate error

• int main(char *argv[])  now if you want to use argc inside


main() error is generated

CS F111 BITS Pilani, Hyderabad Campus


Problem 1 : Count vowels in string

41 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


Problem 2 : check if a string is
palindrome or not ?

42 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


Problem 3 : Hamming Distance

Hamming distance between two strings of equal length is


the number of positions for which the corresponding
symbols are different. Put another way, it measures the
number of substitutions required to change one into the
other, or the number of errors that transformed one string
into the other

For example
String 1 : “123454321”
String 2 : “128454351”

the Hamming distance is 2.

43 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


Problem 3 : Hamming Distance

44 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


Problem 4 : Anagram

Given two string s1, s2 (in lowercase). Determine


whether they are anagram of each other or not ?

For example :

s1 : “australia”
s2 : “utsralaai”

yes they are anagram.

45 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


Problem 4 : Anagram

46 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


Another Approach : Anagram

47 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


Problems : String Manipulations

Problems to be solved without using library functions

1.Copy a string s1 to string s2


http://pastebin.com/nxgBhsSB

2.Concatenate a string s1 with s2


http://pastebin.com/dvVL970Y

3. Compare two string s1, s2 and check if s1 is equal,


greater or smaller than s2.
http://pastebin.com/vUWwQMjx
48 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus
2D character array

• To store list of strings / words we require to use 2D


array
• Each row of the table(2D array) can store a string.
• Make sure that number of columns in 2D array is
large enough to store the longest string

• Declaration :
char words[50][30];

49 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


Display 2D array

50 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


Sorting the list of names

51 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


Tokenizing a sentence into words
Example problem

52 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


Dynamic Memory
Management
• Library Functions
• malloc
• calloc
• free
• realloc

53 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


Dynamic Memory Allocation

Header File : stdlib.h

Function for allocating memory


•malloc()
•calloc()

Function for de-allocating memory


•free()

Function for re-sizing the memory


•realloc()
54 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus
malloc() : allocation
; // function declaration
• returns the base address
• Uninitialized memory

can also write *(a + i) = some


value for initialization

size_t  unsigned integer type


used to represent the sizes of
objects. The result of the sizeof
operator is of this type

55 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


calloc(): allocation

; // declaration
• returns the base address
• memory initialized to 0

56 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


free() : deallocation

; // function declaration

• data might or might not be erased


• if you print after free, you might get
0 or garbage value

57 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


realloc() : resize memory

; // declaration
• Changes the size
• If new size > old size then new space is allocated
• previous contents are copied
• remaining are uninitialized (may be 0 or garbage
value)
• If request cannot be satisfied then p does not change
• If new size < old size, same space is reallocated
• returns pointer to the new space

58 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


realloc() : resize memory

if you write free(a)


here, prog. will
abort

59 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


realloc() : resize memory

If you write
int * a = (int *)malloc(n * sizeof(int));
a = realloc(a, 0);
it is as if you are freeing memory
values present in old block will become uninitialized (0 or
garbage values)
After statement a = realloc(a, 0);
if you try to access the elements as pointed to by a, you may
get a segmentation fault.

60 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


Dynamically allocate 2D array

61 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


Free 2D array

int main()
{
int **a, i;
a = (int **)malloc(4*sizeof(int));
for(i=0;i<4;i++)
a[i] = (int *)malloc(5*sizeof(int));
for(i=0;i<4;i++)
{
free(a[i]);
}
free(a);
return 0;
}

62 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


Few outputs

int main() OUTPUT


{ The elements are:
int *a,n = 5,i; 1
a = (int *)malloc(n*sizeof(int)); 2
for(i=0;i<n;i++) 3
a[i] = i+1; 4
printf("\n The elements are:"); 5
for(i = 0; i <n;i++) Segmentation fault(core dumped)
printf("\n%d",a[i]);
a = realloc(a,0);
for(i = 0; i <n;i++)
printf("\n%d",a[i]);
return 0;

63 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


Few outputs
int main() OUTPUT
{ The elements are:
int *a,n = 5,i; 1
a = (int *)malloc(n*sizeof(int)); 2
for(i=0;i<n;i++) 3
a[i] = i+1; 4
printf("\n The elements are:"); 5
for(i = 0; i <n;i++) 0 might also give
printf("\n%d",a[i]); 2 garbage value in
int *b = realloc(a,0); 3 place of this
for(i = 0; i <n;i++) 4
printf("\n%d",a[i]); 5
return 0;
}

But if you try to print b[i] inside the loop, you will get
segmentation fault

64 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


Few outputs

int main() OUTPUT


{ The elements are:
int *a,n = 5,i; 1
a = (int *)malloc(n*sizeof(int)); 2
for(i=0;i<n;i++) 3
a[i] = i+1; 4
printf("\n The elements are:"); 5
for(i = 0; i <n;i++) 0 might also give
printf("\n%d",a[i]); 2 garbage value in
int *b = a; 3 place of this
a = realloc(a,0); 4
for(i = 0; i <n;i++) 5
printf("\n%d",b[i]);
return 0;

65 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


Few outputs

int main() OUTPUT


{ 1.000000 0x886f008
int n = 6, i; 2.000000 0x886f010
double *a; 3.000000 0x886f018
a = (double *)malloc(n*sizeof(int)); 0.000000 0x886f020
for(i = 0; i < n; i++) 0.000000 0x886f028
a[i] = i + 1; 0.000000 0x886f030
for(i = 0; i < n; i++)
printf(“\n%lf %p”, a[i], &a[i]); But might be compiler dependent
return 0; also

66 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus


THANK YOU

67 17/Nov/2018 CS F111 BITS Pilani, Hyderabad Campus

You might also like