Lecture 15_Strings and Dynamic Memory Allocation.pptx
1. Strings and Dynamic
Memory Allocation
Strings in C (With Examples) (programiz.com)
Course No.
Credit Hours:
Class Hours: Friday 15:00-19:00 , AI Center B203
Office Hours: Monday – Friday: 8:00 am – 10:00 am
2. Strings
In C programming, a string is a sequence of characters terminated with a
null character 0. For example: char c[] = "c string";
When the compiler encounters a sequence of characters enclosed in the
double quotation marks, it appends a null character 0 at the end by
default.
Memory diagram of strings in C programming
4. Initialize strings
You can initialize strings in a number of ways.
char c[] = "abcd";
char c[50] = "abcd";
char c[] = {'a', 'b', 'c', 'd', '0'};
char c[5] = {'a', 'b', 'c', 'd', '0'};
Let's take another example:
char c[5] = "abcde";
Here, we are trying to assign 6 characters (the last character is
'0') to a char array having 5 characters. This is bad and you
should never do this.
5. Assigning Values to Strings
Arrays and strings are second-class citizens in C; they do not support
the assignment operator once it is declared. For example,
char c[100];
c = "C programming"; // Error! array type is not assignable.
Note: Use the strcpy() function to copy the string instead.
6. Read String from the user
use the scanf() function to read a string.
The scanf() function reads the sequence of characters until it encounters whitespace (space, newline,
tab, etc.).
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}
Output
Enter name: Dennis Ritchie
Your name is Dennis.
Note:
Even though Dennis Ritchie was entered in the above program,
only "Dennis" was stored in the name string. It's because there
was a space after Dennis.
the name in scanf() already points to the address of the first
element in the string, which is why we don't need to use &.
7. Read a line of text
You can use the fgets() function to read a line of string. And, you can use puts() to display the string.
#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
fgets(name, sizeof(name), stdin); // read string
printf("Name: ");
puts(name); // display string
return 0;
}
Output:
Enter name: Tom Hanks
Name: Tom Hanks
Note: The gets() function can also be to take input from the user.
However, it is removed from the C standard.
It's because gets() allows you to input any length of characters.
Hence, there might be a buffer overflow.
8. Loop Through a String
char carName[] = "Volvo";
int i;
for (i = 0; i < 5; ++i) {
printf("%cn", carName[i]);
}
Why do we include the 0 character at the end? This is known as the "null terminating character", and must
be included when creating strings using this method. It tells C that this is the end of the string.
9. Passing Strings to Functions
#include <stdio.h>
void displayString(char str[]);
int main()
{
char str[50];
printf("Enter string: ");
fgets(str, sizeof(str), stdin);
displayString(str); // Passing string to a function.
return 0;
}
void displayString(char str[])
{
printf("String Output: ");
puts(str);
}
10. Strings and Pointers
#include <stdio.h>
int main(void) {
char name[] = "Harry Potter";
printf("%c", *name); // Output: H
printf("%c", *(name+1)); // Output: a
printf("%c", *(name+7)); // Output: o
char *namePtr;
namePtr = name;
printf("%c", *namePtr); // Output: H
printf("%c", *(namePtr+1)); // Output: a
printf("%c", *(namePtr+7)); // Output: o
}
11. strlen()
The strlen() function calculates
the length of a given string.
The strlen() function takes a
string as an argument and
returns its length. The returned
value is of type size_t (an
unsigned integer type).
It is defined in the <string.h>
header file.
#include <stdio.h>
#include <string.h>
int main()
{
char a[20]="Program";
char b[20]={'P','r','o','g','r','a','m','0'};
// using the %zu format specifier to print size_t
printf("Length of string a = %zu n",strlen(a));
printf("Length of string b = %zu n",strlen(b));
return 0;
}
Output:
Length of string a = 7
Length of string b = 7
Note that the strlen() function doesn't count the null character 0 while calculating the length.
12. strcpy()
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "C programming";
char str2[20];
// copying str1 to str2
strcpy(str2, str1);
puts(str2); // C programming
return 0;
}
Output:
C programming
Note: When you use strcpy(), the size of the destination string
should be large enough to store the copied string. Otherwise, it
may result in undefined behavior.
13. strcmp()
The strcmp() compares two strings character by character. If the strings are equal, the function returns 0.
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "abcd", str2[] = "abCd", str3[] = "abcd";
int result;
// comparing strings str1 and str2
result = strcmp(str1, str2);
printf("strcmp(str1, str2) = %dn", result);
// comparing strings str1 and str3
result = strcmp(str1, str3);
printf("strcmp(str1, str3) = %dn", result);
return 0;
}
Output:
strcmp(str1, str2) = 1
strcmp(str1, str3) = 0
strings str1 and str2 are not equal. Hence, the result is
a non-zero integer.
strings str1 and str3 are equal. Hence, the result is 0.
Return Value from strcmp()
Return Value Remarks
0 if strings are equal
>0 if the first non-matching character in str1
is greater (in ASCII) than that of str2.
<0 if the first non-matching character in str1
is lower (in ASCII) than that of str2.
The strcmp() function is defined in the string.h header file.
14. strcat()
#include <stdio.h>
#include <string.h>
int main() {
char str1[100] = "This is ", str2[] = "programiz.com";
// concatenates str1 and str2
// the resultant string is stored in str1.
strcat(str1, str2);
puts(str1);
puts(str2);
return 0;
}
Output
This is programiz.com
programiz.com
Note: When we use strcat(), the size of the
destination string should be large enough to
store the resultant string. If not, we will get the
segmentation fault error.
The strcat() function concatenates the
destination string and the source string, and the
result is stored in the destination string.
15. Strings - Special Characters
char txt[] = "We are the so-called "Vikings" from the north.";
The solution to avoid this problem, is to use the backslash escape
character. The backslash () escape character turns special characters
into string characters:
Escape character Result Description
’ ‘ Single quote
" " Double quote
Backslash
The sequence " inserts a double quote in a string:
Example
char txt[] = "We are the so-called "Vikings" from the north.";
char txt[] = "It's alright.";
char txt[] = "The character is
called backslash.";
Escape Character Result
n New Line
t Tab
0 Null
16.
17. Dynamic Memory Allocation
C is a structured language; it has some fixed rules for programming.
One of them includes changing the size of an array. An array is a
collection of items stored at contiguous memory locations.
17
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() - GeeksforGeeks
18. Dynamic Memory Allocation
As it can be seen that the length (size) of the array above made is 9. But
what if there is a requirement to change this length (size). For Example,
If there is a situation where only 5 elements are needed to be entered in
this array. In this case, the remaining 4 indices are just wasting memory
in this array. So there is a requirement to lessen the length (size) of the
array from 9 to 5.
Take another situation. In this, there is an array of 9 elements with all 9
indices filled. But there is a need to enter 3 more elements in this array.
In this case, 3 indices more are required. So the length (size) of the array
needs to be changed from 9 to 12.
18
19. Dynamic Memory Allocation
This procedure is referred to as Dynamic Memory Allocation in C.
Therefore, C Dynamic Memory Allocation can be defined as a procedure in
which the size of a data structure (like Array) is changed during the runtime.
C provides some functions to achieve these tasks. There are 4 library
functions provided by C defined under <stdlib.h> header file to facilitate
dynamic memory allocation in C programming. They are:
1.malloc()
2.calloc()
3.free()
4.realloc()
19
20. C mallo() method
The “malloc” or “memory allocation” method in C is used to dynamically
allocate a single large block of memory with the specified size. It returns a
pointer of type void which can be cast into a pointer of any form. It doesn’t
Initialize memory at execution time so that it has initialized each block with
the default garbage value initially.
Syntax of malloc() in C
ptr = (int*) malloc(100 * sizeof(int));
Since the size of int is 4 bytes, this statement will allocate 400 bytes of
memory. And the pointer ptr holds the address of the first byte in the allocated
memory.
20
If space is insufficient, allocation fails and returns a NULL pointer.
21. Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int* ptr;
int n, i;
// Get the number of elements for the array
printf("Enter number of elements:");
scanf("%d",&n);
printf("Entered number of elements: %dn", n);
// Dynamically allocate memory using malloc()
ptr = (int*)malloc(n * sizeof(int));
// Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL) {
printf("Memory not allocated.n");
exit(0);
}
21
else {
// Memory has been successfully
allocated
printf("Memory successfully allocated
using malloc.n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
return 0;
}
Output:
Enter number of elements: 5
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5,
22. C calloc() method
“calloc” or “contiguous allocation” method in C is used to dynamically allocate the
specified number of blocks of memory of the specified type. it is very much similar to
malloc() but has two different points and these are:
It initializes each block with a default value ‘0’.
It has two parameters or arguments as compare to malloc().
Syntax of calloc() in C
ptr = (cast-type*)calloc(n, element-size);
here, n is the no. of elements and element-size is the size of each element.
For Example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for 25 elements each with the size of
the float.
22
If space is insufficient, allocation fails and returns a NULL pointer.
23. Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int* ptr;
int n, i;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %dn", n);
// Dynamically allocate memory using calloc()
ptr = (int*)calloc(n, sizeof(int));
// Check if the memory has been successfully
// allocated by calloc or not
if (ptr == NULL) {
printf("Memory not allocated.n");
exit(0);
}
23
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using calloc.n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
return 0;
}
Output:
Enter number of elements: 5
Memory successfully allocated using calloc.
The elements of the array are: 1, 2, 3, 4, 5,
24. C free() method
“free” method in C is used to dynamically de-allocate the memory. The
memory allocated using functions malloc() and calloc() is not de-
allocated on their own. Hence the free() method is used, whenever the
dynamic memory allocation takes place. It helps to reduce wastage of
memory by freeing it.
Syntax of free() in C
free(ptr);
24
25. Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int *ptr, *ptr1;
int n, i;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %dn", n);
// Dynamically allocate memory using malloc()
ptr = (int*)malloc(n * sizeof(int));
// Dynamically allocate memory using calloc()
ptr1 = (int*)calloc(n, sizeof(int));
// Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL || ptr1 == NULL) {
printf("Memory not allocated.n"); 25
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using malloc.n");
// Free the memory
free(ptr);
printf("Malloc Memory successfully freed.n");
// Memory has been successfully allocated
printf("nMemory successfully allocated using calloc.n");
// Free the memory
free(ptr1);
printf("Calloc Memory successfully freed.n");
}
return 0;
}
Output:
Enter number of elements: 5
Memory successfully allocated using malloc.
Malloc Memory successfully freed.
Memory successfully allocated using calloc.
Calloc Memory successfully freed.
26. C realloc() method
“realloc” or “re-allocation” method in C is used to dynamically change the
memory allocation of a previously allocated memory. In other words, if the
memory previously allocated with the help of malloc or calloc is insufficient,
realloc can be used to dynamically re-allocate memory. re-allocation of
memory maintains the already present value and new blocks will be
initialized with the default garbage value.
Syntax of realloc() in C
ptr = realloc(ptr, newSize);
where ptr is reallocated with new size 'newSize'.
26
If space is insufficient, allocation fails and returns a NULL pointer.
27. Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int* ptr;
int n, i;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %dn", n);
// Dynamically allocate memory using calloc()
ptr = (int*)calloc(n, sizeof(int));
// Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL) {
printf("Memory not allocated.n");
exit(0);
}
27
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using calloc.n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
// Get the new size for the array
n = 10;
printf("nnEnter the new size of the array: %dn", n);
// Dynamically re-allocate memory using realloc()
ptr = realloc(ptr, n * sizeof(int));
// Memory has been successfully allocated
printf("Memory successfully re-allocated using realloc.n");
// Get the new elements of the array
for (i = 5; i < n; ++i) {
ptr[i] = i + 1;
}
Output:
Enter number of elements: 5
Memory successfully allocated using calloc.
The elements of the array are: 1, 2, 3, 4, 5,
Enter the new size of the array: 10
Memory successfully re-allocated using
realloc.
The elements of the array are: 1, 2, 3, 4, 5, 6,
7, 8, 9, 10,
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
free(ptr);
}
return 0;
}
28. Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
int index = 0, i = 0, n,
*marks; // this marks pointer hold the base
address
// of the block created
int ans;
marks = (int*)malloc(sizeof(
int)); // dynamically allocate memory using
malloc
// check if the memory is successfully allocated
by
// malloc or not?
if (marks == NULL) {
printf("memory cannot be allocated");
}
else {
// memory has successfully allocated
printf("Memory has been successfully
allocated by "
"using mallocn");
printf("n marks = %pcn",
marks); // print the base or beginning
// address of allocated memory
do {
printf("n Enter Marksn");
scanf("%d", &marks[index]); // Get the
marks
printf("would you like to add more(1/0):
");
scanf("%d", &ans);
28
if (ans == 1) {
index++;
marks = (int*)realloc(
marks,
(index + 1)
* sizeof(
int)); // Dynamically reallocate
// memory by using realloc
// check if the memory is successfully
// allocated by realloc or not?
if (marks == NULL) {
printf("memory cannot be allocated");
}
else {
printf("Memory has been successfully "
"reallocated using realloc:n");
printf(
"n base address of marks are:%pc",
marks); ////print the base or
///beginning address of
///allocated memory
}
}
} while (ans == 1);
// print the marks of the students
for (i = 0; i <= index; i++) {
printf("marks of students %d are: %dn ", i,
marks[i]);
}
free(marks);
}
return 0;
}