π Strings in C Programming – Memory Explanation, String Functions, Fully Commented Programs, Viva Questions & MCQs (Beginner to Advanced Guide)
π§π» Introduction
In C programming, we learned about:
-
Variables
-
Arrays
-
Pointers
-
Structures
But what if we want to store text like a name, city, or message?
π That’s where Strings come into the picture.
A String in C is a collection of characters stored in a character array and terminated by a special character called the null character (\0).
π Why Are Strings Important?
Strings are used in:
-
User input (name, address, email)
-
File handling
-
Password validation
-
Data processing
-
Almost every real-world application
π Without strings, real programs cannot interact with users properly.
π Real-Life Analogy
π Think of a string like a train of characters.
Each character is a compartment, and the last compartment contains a special signal (\0) that says:
“Train Ends Here.”
Without that signal, the computer doesn’t know where the string stops.
π§ How Strings Are Stored in Memory
char name[] = "Krishna"; // Declares a character array named 'name' and stores the string "Krishna" in it (including the null character '\0')
π Memory Table Representation
| Address | Value |
|---|---|
| 1000 | 'K' |
| 1001 | 'r' |
| 1002 | 'i' |
| 1003 | 's' |
| 1004 | 'h' |
| 1005 | 'n' |
| 1006 | 'a' |
| 1007 | '\0' |
π¦ Visual Memory Box Representation
| K | r | i | s | h | n | a | \0 |
⚠ The \0 is automatically added by the compiler and marks the end of string.
πΉ Ways to Declare Strings in C
1️⃣ Using Character Array
char name[10] = "Krishna"; // Declares a character array of size 10 and initializes it with "Krishna"; remaining elements are filled with '\0'
2️⃣ Without Size (Compiler Calculates)
char name[] = "Krishna"; // Declares a character array and automatically sets its size based on the string length (including the '\0' null terminator)
3️⃣ Character by Character
char name[] = {'K','r','i','s','h','n','a','\0'}; // Declares a character array and manually initializes each character, including the null terminator '\0' at the end
πΉ Basic String Input & Output
#include <stdio.h> // Standard input-output header file int main() { char name[20]; // Declares a character array to store the user's name (max 19 characters + '\0') printf("Enter your name: "); // Asks user to enter their name scanf("%s", name); // Takes input from user and stores it in 'name' printf("Your name is: %s", name); // Prints the entered name return 0; // Indicates successful program execution }
⚠ scanf("%s") stops at space.
For full line input:
fgets(name, sizeof(name), stdin);
πΉ Common String Functions (string.h)
#include <string.h> // Header file that provides string handling functions like strlen(), strcpy(), strcmp(), strcat(), etc.
1️⃣ strlen() – Find Length
printf("Length = %lu", strlen(str)); // Prints the length of the string 'str' using strlen(); %lu is used because strlen() returns an unsigned long value
2️⃣ strcpy() – Copy String
strcpy(destination, source); // Copies the string from 'source' into 'destination' (including the '\0' null terminator)
3️⃣ strcat() – Concatenate Strings
strcat(str1, str2); // Appends (concatenates) the string 'str2' to the end of 'str1' (adds str2 after str1, including the '\0' terminator)
4️⃣ strcmp() – Compare Strings
int result = strcmp(str1, str2); // Compares two strings 'str1' and 'str2' and stores the result: // 0 → if both strings are equal // <0 → if str1 comes before str2 (lexicographically) // >0 → if str1 comes after str2
In case you want a quick revision, here is a summarized table of all important string functions in C for easy reference.
π₯ Manual String Length Program (Without strlen)
while (str[length] != '\0') // Loop continues until the null terminator '\0' is found { length++; // Increments length to count each character in the string }
π Advanced Concept – Strings & Pointers
char *str = "Krishna"; // Declares a pointer to a string literal "Krishna"; // 'str' points to read-only memory, so the string should not be modified
⚠ Stored in read-only memory. Should not be modified.
π Practice Programs on Strings
πΉ 1️⃣ Program to Reverse a String
π Explanation:
This program reverses the string using a loop by swapping characters from start and end.
#include <stdio.h> // For input and output functions #include <string.h> // For strlen() function int main() { char str[100]; // Array to store the input string (max 99 characters + '\0') int i, length; // 'i' for loop counter, 'length' to store string length char temp; // Temporary variable used for swapping characters printf("Enter a string: "); scanf("%s", str); // Takes string input (stops at space) length = strlen(str); // Finds the length of the string // Loop runs only till half of the string for(i = 0; i < length/2; i++) { temp = str[i]; // Store current character str[i] = str[length - i - 1]; // Replace with corresponding last character str[length - i - 1] = temp; // Place stored character at the end } printf("Reversed string: %s", str); // Prints reversed string return 0; // Program executed successfully }
πΉ 2️⃣ Program to Check Palindrome String
π Explanation:
A palindrome reads same forward and backward (e.g., madam).
#include <stdio.h> // Includes standard input-output functions like printf() and scanf() #include <string.h> // Includes string functions like strlen() int main() // Main function where program execution starts { char str[100]; // Declares a character array to store the string (max 99 chars + '\0') int i, length, flag = 0; // 'i' for loop counter, 'length' for string length // 'flag' initialized to 0 (0 = palindrome, 1 = not palindrome) printf("Enter a string: "); // Displays message to ask user for input scanf("%s", str); // Reads string input from user (stops at space) length = strlen(str); // Calculates length of the string and stores in 'length' for(i = 0; i < length/2; i++) // Loop runs from start to middle of the string { if(str[i] != str[length - i - 1]) // Compares first and last characters { flag = 1; // If characters don't match, set flag to 1 break; // Exit loop immediately if mismatch found } } if(flag == 0) // If flag is still 0 (no mismatch found) printf("Palindrome"); // Print Palindrome else // If flag is 1 (mismatch found) printf("Not Palindrome"); // Print Not Palindrome return 0; // Ends program and returns 0 (successful execution) }
πΉ 3️⃣ Program to Count Vowels and Consonants
π Explanation:
Loops through each character and checks vowel condition.
#include <stdio.h> // Includes standard input-output functions int main() // Main function where execution begins { char str[100]; // Character array to store the input string (max 99 characters + '\0') int i = 0, vowels = 0, consonants = 0; // 'i' for loop index // 'vowels' to count number of vowels // 'consonants' to count number of consonants printf("Enter a string: "); // Prompts user to enter a string scanf("%s", str); // Reads string input (stops at space) while(str[i] != '\0') // Loop continues until null terminator is reached { // Check if character is a vowel (both lowercase and uppercase) if(str[i]=='a'||str[i]=='e'||str[i]=='i'||str[i]=='o'||str[i]=='u'|| str[i]=='A'||str[i]=='E'||str[i]=='I'||str[i]=='O'||str[i]=='U') { vowels++; // Increment vowel counter } // Check if character is an alphabet letter else if((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) { consonants++; // Increment consonant counter } i++; // Move to next character } printf("Vowels = %d\n", vowels); // Prints total number of vowels printf("Consonants = %d", consonants); // Prints total number of consonants return 0; // Indicates successful program execution }
πΉ 4️⃣ Program to Convert Lowercase to Uppercase
π Explanation:
Uses ASCII values to convert lowercase letters.
#include <stdio.h> // Includes standard input-output functions int main() // Main function where program execution starts { char str[100]; // Character array to store the input string (max 99 chars + '\0') int i = 0; // 'i' used as index to traverse the string printf("Enter a string: "); // Prompts user to enter a string scanf("%s", str); // Reads string input (stops at space) while(str[i] != '\0') // Loop continues until null terminator is reached { // Check if character is lowercase letter if(str[i] >= 'a' && str[i] <= 'z') { str[i] = str[i] - 32; // Convert lowercase to uppercase using ASCII value difference } i++; // Move to next character } printf("Uppercase string: %s", str); // Print converted uppercase string return 0; // Ends program successfully }
πΉ 5️⃣ Program to Compare Two Strings Without strcmp()
π Explanation:
Compares character by character manually.
#include <stdio.h> // Includes standard input-output functions int main() // Main function where program execution begins { char str1[100], str2[100]; // Arrays to store two input strings int i = 0, flag = 0; // 'i' for index, 'flag' to check equality (0 = equal, 1 = not equal) printf("Enter first string: "); // Ask user for first string scanf("%s", str1); // Read first string (stops at space) printf("Enter second string: "); // Ask user for second string scanf("%s", str2); // Read second string // Loop continues until both strings reach their null terminator while(str1[i] != '\0' || str2[i] != '\0') { if(str1[i] != str2[i]) // Compare characters at same position { flag = 1; // If mismatch found, set flag to 1 break; // Exit loop immediately } i++; // Move to next character } if(flag == 0) // If no mismatch found printf("Strings are equal"); // Print equal message else // If mismatch found printf("Strings are not equal"); // Print not equal message return 0; // End program successfully }
⚠ Common Mistakes Beginners Make
❌ Forgetting \0
❌ Using == to compare strings
❌ Not allocating enough memory
❌ Using gets() (unsafe function)
π Exam Trap Section (Very Important)
⚠ Students often lose marks because:
-
They forget to include
string.h -
They use
==instead ofstrcmp() -
They do not allocate extra space for
\0 -
They assume
scanf()reads full sentence
Always remember these points in exams.
π Related Topics (Internal Linking for SEO)
To understand strings better, you should also read:
-
Arrays in C
-
Pointers in C
-
Dynamic Memory Allocation in C
These concepts are strongly connected with strings.
π― Viva Questions with Answers
1️⃣ What is a string in C?
π A string in C is a collection of characters stored in a character array and terminated by a null character \0.
2️⃣ What is null character?
π Null character (\0) is a special character that indicates the end of a string.
3️⃣ Difference between char array and string?
π A char array may not contain \0, but a string must always end with \0.
4️⃣ Why do we use string.h?
π To use built-in string functions like strlen(), strcpy(), strcat(), and strcmp().
5️⃣ What does strcmp() return?
π It returns:
-
0 if strings are equal
-
Negative value if first string < second
-
Positive value if first string > second
6️⃣ Why is gets() unsafe?
π Because it does not check buffer size, which can cause buffer overflow.
7️⃣ Difference between scanf() and fgets()?
π scanf("%s") stops at space, while fgets() reads full line including spaces.
8️⃣ Can we modify string literal? Why?
π No. Because string literals are stored in read-only memory.
π§ MCQs (5 Questions)
1️⃣ What is the size of "Hello"?
A) 5
B) 6
C) 4
D) Depends
✅ Answer: B
π Because it includes 5 characters + 1 null character (\0).
2️⃣ Which function compares two strings?
A) strcompare()
B) strcmp()
C) compare()
D) strcheck()
✅ Answer: B
π strcmp() compares characters of two strings and returns 0 if they are equal.
3️⃣ Required header file?
A) stdio.h
B) conio.h
C) string.h
D) math.h
✅ Answer: C
π All standard string functions like strlen(), strcpy(), and strcmp() are declared in string.h.
4️⃣ Which symbol represents end of string?
A) \n
B) \t
C) \0
D) EOF
✅ Answer: C
π The null character \0 marks the end of a string in C.
5️⃣ Which operator compares string addresses?
A) ==
B) =
C) !=
D) >
✅ Answer: A
π The == operator compares memory addresses, not actual string contents.
π₯ Advanced Interview-Level Questions with Answers
1️⃣ What is the difference between char str[] = "Hello"; and char *str = "Hello";?
π In first case, memory is allocated in stack and modifiable.
π In second case, string literal stored in read-only memory and should not be modified.
2️⃣ What happens if a string is not null-terminated?
π The program may access garbage memory and cause undefined behavior.
3️⃣ Explain time complexity of strlen()?
π Time complexity is O(n) because it checks each character until \0.
4️⃣ Why should we avoid using gets()?
π Because it does not limit input size and can cause buffer overflow vulnerability.
5️⃣ How can you dynamically allocate memory for a string?
π Using malloc():
char *str = (char*)malloc(20 * sizeof(char)); // Dynamically allocates memory for 20 characters on the heap // Returns a pointer to the first byte of allocated memory // Typecasting (char*) converts void pointer returned by malloc() // Memory must be freed later using free(str);
And free using:
free(str); // Releases (deallocates) the dynamically allocated memory pointed to by 'str' // Prevents memory leaks by returning heap memory back to the system // After this, 'str' becomes a dangling pointer unless set to NULL
π Conclusion
Strings are one of the most important concepts in C programming.
✔ Used for text handling
✔ Important in file handling
✔ Required for user input
✔ Frequently asked in interviews
✔ Critical for advanced C concepts
Mastering strings makes your C foundation very strong.
π Keep Learning. Keep Coding. Keep Growing.
✨ Written by Krishna Popat
π± Founder, Learning Growth Hub
Excellent ππ»✨
ReplyDeleteThank You✨
Delete