Bird
0
0
DSA Cprogramming

How Strings Work Differently Across Languages in DSA C - Step-by-Step

Choose your learning style9 modes available
Mental Model
Strings are stored and handled differently in each language, affecting how we use and change them.
Analogy: Think of strings like different types of containers: some are fixed boxes (arrays), some are stretchy bags (dynamic strings), and some are special boxes with labels (objects).
C string (array):
[H][e][l][l][o][\0]
↑ start pointer

Python string (immutable):
"Hello"

Java string (object):
String object -> [H][e][l][l][o]
Dry Run Walkthrough
Input: C string: char str[] = "Hi"; change str[1] to 'a'
Goal: Show how changing a character in a C string array works directly
Step 1: Initialize string array with characters 'H', 'i', and null terminator
[H][i][\0]
↑ str[0]
Why: We need to store characters in a fixed array with an end marker
Step 2: Change character at index 1 from 'i' to 'a'
[H][a][\0]
↑ str[0]
Why: Arrays allow direct modification of characters
Step 3: Print the string
Output: Ha
Why: Shows the string changed successfully
Result:
[H][a][\0]
Output: Ha
Annotated Code
DSA C
#include <stdio.h>

int main() {
    char str[] = "Hi"; // Initialize string array
    str[1] = 'a'; // Change second character
    printf("%s\n", str); // Print modified string
    return 0;
}
char str[] = "Hi";
Create a fixed array of characters with null terminator
str[1] = 'a';
Modify character directly in the array
printf("%s\n", str);
Print the string until null terminator
OutputSuccess
Ha
Complexity Analysis
Time: O(n) to print the string because it reads characters until null terminator
Space: O(n) for storing n characters plus one null terminator
vs Alternative: In languages with immutable strings, changing a character requires creating a new string, which is slower and uses more memory
Edge Cases
Empty string (char str[] = "")
Array contains only the null terminator; printing shows nothing
DSA C
char str[] = "";
Trying to modify a string literal (char *str = "Hi")
Undefined behavior or crash because string literals are read-only
DSA C
Use char array instead of pointer to string literal
When to Use This Pattern
When you see string manipulation in C, remember strings are arrays of chars ending with '\0', so direct modification is possible only if stored in arrays, not literals.
Common Mistakes
Mistake: Modifying a string literal through a pointer causes crash
Fix: Use a char array to store the string if you want to modify it
Summary
Strings in C are arrays of characters ending with a null character, allowing direct modification if stored in arrays.
Use this when you need to change characters in a string efficiently in C.
Remember that string literals are read-only and must not be changed directly.