Download BPOPS Module 4 — Strings & Pointers in C: The Complete Study Guide and more Study notes C programming in PDF only on Docsity!
BPOPS103 / 203
MODULE 4 — COMPLETE STUDY
NOTES
Strings & Pointers in C Programming
A fully expanded, exam-ready guide with detailed explanations, worked examples, memory
diagrams, comparison tables, solved programs, and practice / viva questions for every topic.
What's inside this guide
Part A Strings in C — declaration, initialization, reading/writing, string taxonomy, and
every core string operation (length, case conversion, concatenation,
comparison, reversal, substrings, insert/delete/replace)
Part B Standard string library functions (strcat, strcpy, strcmp, strlen, strstr, and
more), arrays of strings, and Pointers in C — declaration, initialization, types,
and passing arguments via pointers
Extras Worked examples, memory diagrams, comparison tables, common mistakes,
exam-style questions, viva Q&A, and a quick-revision cheat sheet
Prepared as an extended companion to the BPOPS103/203 Module 4 curriculum (Strings and Pointers), designed for
quick understanding and thorough revision.
TABLE OF CONTENTS
A.1 Introduction to Strings
A.2 Declaration and Initialization of Strings
A.3 Reading Strings
A.4 Writing (Displaying) Strings
A.5 String Taxonomy
A.6 String Operations
A.7 Part A — Quick Revision Sheet
A.8 Practice Questions — Part A
A.9 Viva-Voce Questions — Part A
B.1 Miscellaneous String and Character Functions
B.2 String Manipulation Functions (string.h)
B.3 Array of Strings
B.4 Pointers in C
B.5 Passing Arguments to Functions Using Pointers
B.6 Advantages and Disadvantages of Pointers
B.7 Part B — Quick Revision Sheet
B.8 Practice Questions — Part B
B.9 Viva-Voce Questions — Part B
Consolidated Exam-Prep Checklist
A.1 Introduction to Strings
Think of a string as a sentence written one letter-box at a time. A string is simply a group of characters
placed together, one after another, to form a piece of text — a name, a sentence, a word, or any sequence
of characters. In C, a string is always written enclosed within double quotes ("..."), and every string
always ends with a special hidden character called the null character , written '\0'.
This null character is not visible when you print the string, but it is absolutely essential — it is the delimiter
(marker) that tells C 'the string stops here.' Without it, C would have no way of knowing where a string ends,
since a string is really just a character array with no length information stored separately.
A.1.1 Character vs String — The Crucial Difference
Beginners often confuse a single character with a one-letter string — but C treats them completely
differently in memory.
Declaration Meaning Memory Needed
char ch = 'H'; H is a character, NOT a string. A single quote is used.
1 memory location — just the letter H
char str[] = "H"; H is a string (a 1-character string), because double quotes are used.
2 memory locations — 'H' AND the hidden '\0'
char str[] = "HELLO"; A 5-character string. 6 memory locations — H,E,L,L,O,\
char str[] = ""; An empty string — legal in C. 1 memory location — just '\0'
NOTE — Important Distinction
C permits an empty string (just the null character), but it does NOT allow an empty character — you
cannot write char ch = '';. A character must always hold exactly one symbol.
Visually, for char str[] = "HELLO";, memory looks like this:
H E L L O \
Six memory slots are used — five for the letters, and one final slot for the invisible end-of-string marker.
A.2 Declaration and Initialization of Strings
A string in C is declared exactly like an array of characters — because that is precisely what it is under the
hood.
A.2.1 Declaration
data_type string_name[size];
// Example: char str[10]; // reserves 10 bytes for the string 'str'
A.2.2 Initialization
data_type string_name[size] = value;
Method 1 — Character-by-character initialization
char str[] = {'H', 'e', 'l', 'l', 'o', '\0'};
Here the compiler automatically counts the number of elements provided and reserves exactly that much
space. Since 6 elements (including the null character) are listed, 6 memory slots are reserved for str.
Method 2 — String literal initialization
char str[10] = "HELLO";
Here the compiler creates a character array of size 10, stores the value "HELLO" in the first five slots, and
automatically appends the null character right after it. Every remaining, unused slot in the array is
automatically initialised to NULL (0).
Method 3 — Size smaller than or equal to the string content
char str[5] = "HELLO";
NOTE — Watch out!
"HELLO" needs 6 slots (5 letters + null character), but only 5 were declared here. This is a
boundary-overflow risk — depending on the compiler, it may either raise an error or silently overwrite
adjacent memory. Always leave at least one extra slot for the null terminator.
Memory Representation — char str[6] = "HELLO";
Element Address Value
str[0] 1000 H
str[1] 1001 E
str[2] 1002 L
str[3] 1003 L
str[4] 1004 O
str[5] 1005 \
A.4 Writing (Displaying) Strings
Just as there are three ways to read a string, C also gives us three ways to display one on the screen.
A.4.1 Method 1 — Using printf()
printf("%s", str);
A.4.2 Method 2 — Using puts()
puts(str);
puts() is a simple function that overcomes a minor drawback of printf() (needing a format specifier). It writes
the entire string as one line of output, and automatically terminates that line with a newline character ('\n').
On success it returns a non-negative number; on failure, it returns EOF (-1).
A.4.3 Method 3 — Using putchar() Repeatedly
i=0; while(str[i] != '\0') { putchar(str[i]); // Print the character on the screen i++; }
This walks through the string one character at a time, printing each one individually, and stops the instant it
reaches the null character — this is, in fact, exactly how printf("%s",...) and puts() work internally.
A.5 String Taxonomy
In C, a string can be stored using one of two broad formats — fixed length, or variable length (which is
further split into two sub-types).
string
Fixed length A size is chosen once and never changes
Variable length — Length-controlled The count of characters is tracked/specified explicitly
Variable length — Delimited A special character marks the end of the string
A.5.1 Fixed-Length Strings
When storing a string in a fixed-length format, an appropriate size must be chosen for the string variable in
advance. Choosing a size that is too small means we simply cannot fit all the characters we need.
Choosing a size that is too large , on the other hand, wastes memory that will likely never be used.
A.5.2 Variable-Length Strings
A variable-length string can expand or contract to accommodate however many characters it actually needs
to hold. Example: if we declare a string to store a student's name, and one student's name is 20 characters
long while another's is only 5 characters long, a variable-length string adapts to each case without wasting
space.
Length-Controlled Strings
Here we explicitly specify (and track) the number of characters in the string. This count is then used by
string-manipulation functions to determine the string's actual, current length.
Delimited Strings
Here, the string is simply ended with a chosen delimiter character, which is then used to identify where the
string stops. Just as every English sentence ends with a full stop, C strings can, in principle, use any
character — comma, semicolon, colon, dash, or the null character — as a delimiter. In practice, however,
the null character ('\0') is overwhelmingly the most common delimiter used in C.
puts(upper_str); return 0; } /* Output: enter the string: hello the string converted into upper case is: HELLO */
A.6.3 Converting a String to Lower Case
The reverse conversion follows the same logic in the opposite direction: to convert an uppercase character
to lowercase, we simply add 32 to its ASCII value.
#include #include int main() { char str[100], lower_str[100]; int i=0, j=0; printf("\n enter the string:"); gets(str); while(str[i] != '\0') { if(str[i]>='A' && str[i]<='Z') lower_str[j] = str[i] + 32; else lower_str[j] = str[i]; i++; j++; } lower_str[j] = '\0'; printf("\n the string converted into lower case is:"); puts(lower_str); return 0; } /* Output: Enter the string: Hello The string converted into lower case is: hello */
NOTE — Common Exam Trap
The original notes had a typo in this program, subtracting 32 for lowercase conversion instead of
adding 32. Always double check the arithmetic direction: uppercase-to-lowercase means ADD 32;
lowercase-to-uppercase means SUBTRACT 32.
A.6.4 Concatenating Two Strings
If s1 and s2 are two strings, the concatenation operation produces a brand new string containing all the
characters of s1, immediately followed by all the characters of s2.
#include #include int main() { char str1[100], str2[100], str3[100]; int i=0, j=0; printf("\n enter the first string :"); gets(str1); printf("\n enter the second string:"); gets(str2);
while(str1[i] != '\0') // copy all of str1 into str { str3[j] = str1[i]; i++; j++; } i = 0; while(str2[i] != '\0') // then copy all of str2 into str { str3[j] = str2[i]; i++; j++; } str3[j] = '\0'; // terminate the new string
printf("\n the concatenated string is:"); puts(str3); getch(); return 0; } /* Output: Enter the first string : Hello Enter the second string : How are you? The concatenated string is : HelloHow are you? */
NOTE — Design Tip
This basic version simply glues the two strings together with nothing in between. If you want a space
or comma separating them, insert that character into str3 manually between the two copy loops.
A.6.5 Appending Strings
Appending is a close cousin of concatenation. If s1 is the source string and s2 is the destination string ,
appending copies the contents of s1 onto the end of s2 — the source string s1 stays unchanged, while the
destination string becomes s2 = s2 + s1.
#include #include int main() { char Dest_str[100], source_str[50]; int i=0, j=0; printf("\n enter the source string:"); gets(source_str); printf("\n enter the destination string:"); gets(Dest_str);
while(Dest_str[i] != '\0') // find the end of the destination string i++;
A.6.6 Comparing Two Strings
If s1 and s2 are two strings, comparing them can produce exactly one of three possible results:
- s1 and s2 are equal — every character matches, and both strings are the same length.
- s1 > s2 — in dictionary (lexicographic) order, s1 comes AFTER s2.
- s1 < s2 — in dictionary order, s1 comes BEFORE s2.
The comparison is done character by character (using ASCII values), starting from the very first character,
exactly like alphabetising words in a dictionary.
#include #include #include int main() { char str1[50], str2[50]; int i=0, len1=0, len2=0, same=0; printf("\n enter the first string :"); gets(str1); printf("\n enter the second string "); gets(str2);
len1 = strlen(str1); len2 = strlen(str2);
if(len1 == len2) { while(i < len1) { if(str1[i] == str2[i]) i++; else break; } if(i == len1) { same = 1; printf("\n the two strings are equal"); } } if(len1 != len2) printf("\n the two strings are not equal ");
if(same == 0) { if(str1[i] > str2[i]) printf("\n string1 is greater than string2"); else if(str1[i] < str2[i]) printf("\n string2 is greater than string1"); } getch(); return 0; } /* Output: Enter the first string: Hello Enter the second string: Hello The two strings are equal */
NOTE — Reading the logic
The program first checks if the lengths match. If they do, it compares character by character until
either a mismatch is found or the entire length is scanned. If a mismatch is found (or the lengths
differ), the ASCII value at that position decides which string is 'greater' in dictionary order.
A.6.7 Reversing a String
If s1 = "Hello", then the reverse of s1 is "olleH". To reverse a string, we simply swap the first character with
the last, the second character with the second-last, and so on, working inward from both ends
simultaneously.
NOTE — Library Shortcut
C's string.h library provides a ready-made function strrev(s1) that reverses all characters in a
string except the null character — but it's important to know how to build the logic manually, since it's
a very common exam question.
#include #include #include int main() { char str[100], temp; int i=0, j=0; printf("\n enter the string"); gets(str); j = strlen(str) - 1;
while(i < j) { temp = str[j]; str[j] = str[i]; str[i] = temp; i++; j--; } printf("\n the reversed string is :"); puts(str); getch(); return 0; } /* Output: Enter the string :Hi there The reversed string is: ereht iH */
A.6.10 Indexing
The index operation returns the position in a string where a given pattern first occurs.
Example: INDEX("Welcome to the world of programming", "world") = 15
A.6.11 Deletion
The deletion operation removes a substring from a given text. It is written as DELETE(text, position,
length).
Example: DELETE("ABCDXXXABCD", 5, 3) = "ABCDABCD"
#include #include int main() { char text[200], str[20], new_text[200]; int i=0, j=0, found=0, k, n=0, copy_loop=0; printf("\n enter the main text:"); gets(text); printf("\n enter the string to be deleted:"); gets(str);
while(text[i] != '\0') { j=0; found=0; k=i; while(text[k]==str[j] && str[j]!='\0') { k++; j++; } if(str[j]=='\0') copy_loop = k; else copy_loop = i; new_text[n] = text[copy_loop]; i++; n++; } new_text[n] = '\0'; printf("\n the new string is :"); puts(new_text); getch(); return 0; } /* Output (deleting ",how are you?" from "Hello,how are you?"): Enter the main text :Hello,how are you? Enter the string to be deleted :,how are you? The new string is: Hello */
A.6.12 Replacement
The replacement operation replaces one pattern (p1) inside a text with another pattern (p2). It is written as
REPLACE(text, pattern1, pattern2).
Example: REPLACE("AAABBBCCC", "BBB", "X") = "AAAXCCC"
NOTE — Exam Tip
For insertion, deletion, replacement, and indexing operations, you are usually only required to
describe the operation and demonstrate the syntax with an example, not necessarily write a full
program from scratch — but understanding the programs above (insertion and deletion) will help you
tackle any variant asked.
- Q: Why is scanf("%s", str) unreliable for sentences? A: Because it stops reading at the first blank space.
- Q: What ASCII value difference exists between corresponding upper and lower case letters? A: Exactly
- Q: In appending, which of the two strings changes? A: Only the destination string; the source string stays
unchanged.
- Q: What library function reverses a string automatically? A: strrev(), from string.h.
- Q: What are the three possible outcomes of comparing two strings? A: Equal, s1 > s2, or s1 < s
(dictionary order).
PART B
STRING FUNCTIONS, ARRAYS OF STRINGS & POINTERS