Systems Programming and C Language Definitive Study Guide
Number Systems and Data Representation
Number Systems & Conversions
Four Primary Number Systems:
Decimal: Base , digits to
Binary: Base , digits and
Octal: Base , digits to
Hexadecimal: Base , digits to and to (representing values to )
Purpose: Computers translate letters, words, and characters into binary numbers (s and s) because computer hardware can only operate on binary logic.
Decimal to Binary Conversion (LCM / Division Method):
Repeatedly divide the decimal number by and collect the remainders from bottom to top.
Example: Converting decimal to binary:
Resulting Binary: (or represented in 7-bit form as ).
Verification (Binary to Decimal):

Base Conversions with Octal and Hexadecimal:
Decimal to Octal: Divide by repeatedly. Example: .
Decimal to Hexadecimal: Divide by repeatedly. Example: .
Hexadecimal to Binary:
The maximum hexadecimal digit , which requires bits ().
Convert each hexadecimal digit directly into a -bit binary block.
Example: , , .


* **Octal to Binary**:
* The maximum octal digit requires bits ().
* Convert each octal digit directly into a -bit binary block.
* *Example*: , , .


* **Octal to Hexadecimal Conversion**:
1. Convert octal digits to -bit binary blocks.
2. Group the resulting binary string into -bit blocks from right to left.
3. Map each -bit block to its hexadecimal equivalent.
4. *Example*: .

Data Representation & Signed Numbers
Bit: Derived from "binary digit". The fundamental language of computer hardware, having two states ( or , false or true).
Byte: A collection of bits. It is the smallest addressable unit of storage in computer memory.
Character: A -byte integer translated into human-readable symbols using character sets (ASCII, EBCD, UTF).
In C, characters are enclosed in single quotes (
'a') and stored as their ASCII integer values.Examples:
'0''A'
Word Size: Defines processor capability—the maximum number of bits a CPU can fetch or process in a single clock cycle.
An -bit microcontroller fetches bits per cycle.
A -bit processor fetches bits per cycle.
Integer Representation:
Positive Integers: Represented via direct binary conversion.
Example: Positive in a -bit representation:
0000 0000 0000 0000 0000 0000 0000 1101.
Negative Integers: Stored using 2's Complement notation ().
Example: Storing in a -bit system:
Positive :
0000 0000 0000 0000 0000 0000 0000 11011's Complement:
1111 1111 1111 1111 1111 1111 1111 0010Add :
1111 1111 1111 1111 1111 1111 1111 0011
In an -bit system, can be computed as 256 - 13 = 243_{10} = 1111\,0011_2$.\n\n\n## Floating-Point Representation (IEEE 754 Standard)\n\nReal (fractional) numbers in C are encoded using the **IEEE 754** standard format.\n\n* **Step 1**: Convert integral and fractional parts to binary.\n * To convert fractional decimal to binary, multiply by 2 repeatedly and record integer carries.\n * *Example*: 10.25_{10}\n * Integral part: 10_{10} = 1010_2\n * Fractional part: 0.25 \times 2 = 0.500.50 \times 2 = 1.01\rightarrow .010_2\n * Combined Binary: 1010.010_2\n\n\n\n\n\n* **Step 2**: Normalize the binary value into standard exponent scientific notation (1.Xe^{\pm y}).\n * 1010.010_2 \rightarrow 1.010010_2 \times 2^3\n * Number of shifts y = 3yy).\n * Mantissa (X123 bits: `01001000000000000000000`.\n * Sign bit: 01 for negative.\n\n\n\n* **Step 3**: Calculate Biased Exponent.\n * Standard Bias for 32-bit single-precision float = 127.\n * Exponent = \text{Bias} + y = 127 + 3 = 130_{10} = 1000\,0010_2.\n * Final 32-bit Float Representation (`Sign | Exponent (8 bits) | Mantissa (23 bits)`):\n * `0 | 10000010 | 01001000000000000000000`\n\n\n\n* **IEEE 754 Double Precision (64-bit)**:\n * Sign bit: 1 bit\n * Exponent: 11= 1023\n * Mantissa: 52 bits\n * *Example for Double value 2.5*:\n * Binary = 10.10_2 = 1.010_2 \times 2^1 \rightarrow y = 1\n * Exponent = 1023 + 1 = 1024_{10} = 10000000000_2\n\n* **Repeating Real Numbers**:\n * Some decimal fractions cannot be represented exactly in binary (e.g., 1.7_{10}).\n * 0.7 \times 2 = 1.40.4 \times 2 = 0.80.8 \times 2 = 1.60.6 \times 2 = 1.20.2 \times 2 = 0.4 (0) ... results in infinite repeating mantissa `1.1011001100110...`\n\n\n# C Language Fundamentals: Types, Operators, and Control Flow\n\n## C Data Types & Size Modifiers\n\n* **Primitive / Basic Types**:\n * `int`: Integer type. Storage size is compiler-dependent.\n * Turbo C (16= 2 bytes.\n * GCC (3264= 4 bytes.\n * `char`: 1-byte integer storing ASCII codes.\n * `float`: 4-byte single-precision real format.\n * `double`: 8-byte double-precision real format.\n* **`sizeof` Operator**:\n * Returns object/type size in bytes. Syntaxes: `sizeof(variable)`, `sizeof(data_type)`, `sizeof(constant)`, or `sizeof variable`.\n * Return type: Returns `unsigned int` (`%u`) on 326424812168160 = +1 = -).\n * Range formula: -2^{n-1}+2^{n-1} - 1.\n * For `signed char` (8-2^7+2^7 - 1 = -128+127.\n * `unsigned`: No sign bit; all bits store magnitude. Range formula: 02^n - 1.\n * For `unsigned char` (80255.\n * *Overflow / Underflow Handling*:\n * Assigning `char ch = 133;` (Binary `1000 0101`): Since MSB is 1-123.\n * Assigning `unsigned char ch = -13;`: Interpreted as 2's complement pattern `1111 0011`, which prints as positive 243.\n\n\n## Control Constructs & Loop Efficiency\n\n* **Single Iteration Constructs**:\n * `if` / `else if` / `else`\n * `switch`: Compares an expression against integral constant `case` labels.\n * Rules: Case labels must be unique, integral constants or enums. Floating-point constants (`2.5`) are prohibited.\n * Missing `break` statements cause **fall-through**, executing all subsequent case statements regardless of label matching.\n * *Performance (Switch vs. If-Else)*:\n * `if-else` chains test conditions sequentially (1, 2, 3, 4\dots4200\,\text{ns}= 800\,\text{ns}.\n * `switch` statements compile into a **Jump Table**, branching directly to the destination case in 1200\,\text{ns}).\n* **Multi-Iteration Loops**:\n * `while`: Entry-controlled loop. Evaluates condition before executing body.\n * `do...while`: Exit-controlled loop. Executes body at least once before checking condition. Ideal for menu-driven applications (e.g., ATM transaction prompts, game replay loops).\n * `for(initialisation; condition; post_evaluation)`:\n * Execution Sequence: 1. Initialization \rightarrow\rightarrow\rightarrow\rightarrow 5. Loop back to Step 2.\n* **Loop Nesting Machine Cycle Efficiency**:\n * *Scenario A*: Outer loop 10100 iterations (`for(i=0; i<10; i++) for(j=0; j<100; j++)`)\n * Outer Overhead: 1 \text{ (init)} + 11 \text{ (cond checks)} + 10 \text{ (increment)} = 22 machine cycles.\n * Inner Overhead per outer iteration: 1 + 101 + 100 = 202= 202 \times 10 = 2020 cycles.\n * Total Execution Cycles = 22 + 2020 = 2042 cycles.\n * *Scenario B*: Outer loop 10010 iterations (`for(i=0; i<100; i++) for(j=0; j<10; j++)`)\n * Outer Overhead: 1 + 101 + 100 = 202 cycles.\n * Inner Overhead per outer iteration: 1 + 11 + 10 = 22= 22 \times 100 = 2200 cycles.\n * Total Execution Cycles = 202 + 2200 = 2402 cycles.\n * *Conclusion*: Keeping the smaller loop count on the outside reduces total machine cycles (20422402).\n\n\n\n* **Jump Controls**:\n * `break`: Exits innermost loop or switch block.\n * `continue`: Skips remainder of current iteration and jumps directly to loop post-evaluation/condition test.\n * `goto`: Unconditional jump to a labeled statement. Discouraged in structured programming due to spaghetti control flow.\n\n\n## Operator Mechanics & Bitwise Operations\n\n* **Increment / Decrement Operators**:\n * **Pre-increment (`++x`)**: Increments variable value first, then evaluates expression with new value.\n * **Post-increment (`x++`)**: Evaluates expression with current value first, then increments variable.\n * **Undefined Behaviors**: Expression modifying and accessing a variable multiple times without sequence points produces undefined results (e.g., `y = y++`, `printf("%d %d %d %d\n", ++x, x++, x++, ++x)`).\n* **Type Conversion**:\n * **Implicit Conversion**: Lower-rank types are automatically promoted to higher-rank types in arithmetic operations (e.g., `int / float` promotes `int` to `float`, producing `float`).\n * **Explicit Conversion (Casting)**: `z = (float) x / y;` forces floating-point division.\n * **Integer Promotion**: In expressions involving `char` or `short`, both operands are automatically converted to `int` before arithmetic.\n* **Logical Operators & Short-Circuit (Circuit) Logic**:\n * `&&` (Logical AND): Evaluates to true (1) if both operands are non-zero.\n * `||` (Logical OR): Evaluates to true (1) if at least one operand is non-zero.\n * `!` (Logical NOT): Inverts truth value.\n * *Short-Circuit Evaluation*:\n * In `A || B`: If `A` is true (non-zero), `B` is **never evaluated**.\n * In `A && B`: If `A` is false (0), `B` is **never evaluated**.\n* **Compound Assignment Precedence**:\n * Evaluates right-to-left. `num1 += num2 += num3 += num4;` executes as `num3 = num3 + num4`, then `num2 = num2 + num3`, then `num1 = num1 + num2`.\n\n\n\n* **Bitwise Operators**:\n * Operate directly on individual bits of integer data types.\n * `&` (Bitwise AND): Output bit is 11\n * `|` (Bitwise OR): Output bit is 11\n * `^` (Bitwise XOR): Output bit is 10\text{ vs }1)\n * `~` (Bitwise Complement / 1's Complement): Inverts all bits (0 \rightarrow 11 \rightarrow 0)\n* **Bit Shift Operators**:\n * **Left Shift (`<<`)**: `value << n` shifts bits left by n2^n.\n\n\n\n * **Unsigned Right Shift (`>>`)**: `value >> n` shifts bits right by n2^n.\n\n\n\n * **Signed Right Shift (`>>`)**: Preserves sign bit. MSB is filled with copies of the current sign bit (MSB prior to shift).\n * *Example for negative number*: `signed char ch = -56` (1100\,1000_211111\,0010_2 = -14_{10}-56 / 2^2).\n * *Shift Constraints*: Shift count must be positive and strictly within the bit-width of the operand type (0 \dots 310 \dots 7 for 8-bit `char`). Out-of-bounds shift counts cause undefined behavior.\n\n\n## Bit Manipulation Techniques (Masking)\n\n* **Setting a Bit (Force to 1)**:\n * To set a bit at position `pos`: Use **Bitwise OR** with a mask where bit `pos` is 1\n * Formula: `mask = 1 << pos;` \rightarrow `result = value | mask;` \n * To set lower n\rightarrow `result = value | mask;` \n* **Clearing a Bit (Force to 0)**:\n * To clear a bit at position `pos`: Use **Bitwise AND** with an inverted mask where bit `pos` is 0\n * Formula: `mask = ~(1 << pos);` \rightarrow `result = value & mask;` \n * To clear lower n\rightarrow `result = value & mask;` \n* **Toggling a Bit (Invert 0 to 1, 1 to 0)**:\n * To toggle a bit at position `pos`: Use **Bitwise XOR**.\n * Formula: `mask = 1 << pos;` \rightarrow `result = value ^ mask;` \n\n\n# Memory Layout, Storage Classes, and Linkage\n\n## Operating System Memory Model & User Space\n\n* **Linux OS Division**:\n * **Kernel Space**: Privileged memory housing kernel code, drivers, and core OS data structures.\n * **User Space**: Resticted memory segment where normal user programs execute. User programs cannot directly access kernel space memory. Attempts to access kernel space trigger a **Segmentation Violation** (Segmentation Fault).\n* User space contains multiple active processes (P_1, P_2, P_3, \dots, P_n), each scheduled independently by the operating system kernel.\n\n\n\n\n\n\n## Process Memory Segments\n\nEvery compiled C process loaded into user space memory is partitioned into four major structural segments (plus command-line argument space):\n\n\n\n1. **Text Segment (Code Segment)**:\n * Contains the executable machine instructions of the program.\n * Placed at low memory addresses below heap/stack to prevent accidental overwriting.\n * **Read-only** and fixed in size. Sharable across multiple process instances running the same program.\n2. **Data Segment**:\n * **Initialized Data Segment**: Stores global variables, static variables, and constant static variables that are explicitly initialized with non-zero values by the programmer.\n * **Uninitialized Data Segment (.BSS - Block Started by Symbol)**: Stores uninitialized global and static variables. Automatically zero-filled (0 or `NULL`) by the kernel before program execution begins.\n3. **Heap Segment**:\n * Used for **Dynamic Memory Allocation** at runtime (`malloc()`, `calloc()`, `realloc()`).\n * Begins at the end of the .BSS segment and grows **upward** toward higher memory addresses.\n4. **Stack Segment**:\n * Stores automatic/local variables, function parameter lists, and return addresses.\n * Loaded in the high memory region of user space and grows **downward** toward lower memory addresses.\n5. **Unallocated Hole**: The unallocated virtual address space between the growing Heap and Stack. When the Stack pointer and Heap pointer meet, system memory is exhausted.\n6. **Command Line Arguments & Environment Variables**: Loaded at the top-most region of user space memory above the stack.\n\n\n## Stack Architecture and Call Frames\n\n* **Stack Pointer Register**: A hardware CPU register tracking the current top of the stack. It is adjusted automatically every time a value is pushed or popped.\n* **Stack Frame**: A discrete block of memory pushed onto the stack whenever a function call is made.\n * Contains: **Parameter List**, **Return Address** (address in text segment to resume execution after function return), and **Local Variables**.\n * *Constraint*: Every stack frame contains at least a return address.\n\n\n\n\n\n\n## Storage Classes, Scope, Lifetime, and Linkage\n\nStorage classes define four properties of C variables: Scope (visibility region), Lifetime (duration of existence), Memory Allocation location, and Linkage.\n\n\n\n| Variable Category | Storage Class | Scope | Lifetime | Memory Allocation | Linkage |\n| :--- | :--- | :--- | :--- | :--- | :--- |\n| **Local** | `auto` | Block | Between block entry & exit | Stack | None |\n| **Local** | `register` | Block | Between block entry & exit | CPU Register / Stack | None |\n| **Local** | `static` | Block | Program start to end | Data Segment (.BSS / Init) | None |\n| **Global** | `static` | File | Program start to end | Data Segment (.BSS / Init) | Internal |\n| **Global** | `extern` | Program | Program start to end | Data Segment (.BSS / Init) | External |\n| **Function Parameter** | `register` / default | Function | Function entry & exit | Stack | None |\n\n*Note*: A **Block** is defined as a function body or any nested `{ ... }` block within a function.\n\n* **`auto`**: Default for local variables. Re-allocated on stack upon block entry, destroyed on exit.\n* **`register`**: Requests CPU to store variable in a machine register for high-speed access. Address-of operator `&` **cannot** be applied to a `register` variable (triggers compilation error).\n* **`static` Local**: Retains value across function calls. Allocated once in Data Segment at program startup, initialized once.\n* **`static` Global**: Restricts variable visibility strictly to the current translation unit (`.c` file).\n* **`extern` Global**: Declares a global variable defined elsewhere (in another file or lower down in the same file).\n\n\n## Declaration vs Definition and Linkage Rules\n\n* **Declaration**: Announces the name and type of an identifier to the compiler without allocating memory. Can be declared multiple times.\n* **Definition**: Specifies type AND allocates memory space for the variable. Occurs exactly once.\n* **One Definition Rule (ODR)**: In a given scope, there can be **only one definition** of a variable.\n* **Tentative Definitions**: A global declaration lacking an explicit initializer or `extern` keyword (e.g., `int x;`).\n * Multiple tentative definitions in the same file are merged into a single definition zero-initialized in .BSS at link time.\n* **Translation Unit**: A single source file (`.c`) along with all header files (`.h`) included via `#include` statements.\n* **Linkage Types**:\n * **External Linkage**: Identifier can be referenced across multiple translation units (global non-static variables/functions).\n * **Internal Linkage**: Identifier can only be referenced within its own translation unit (`static` global variables/functions).\n * **None**: Identifier is isolated to its local block (local variables).\n* **Linkage Disagreement Errors**: Declaring a variable with conflicting linkages in the same translation unit (e.g., `extern int x;` followed by `static int x;`) causes a compilation error.\n\n\n# C Standard Input / Output (stdio)\n\n## File Descriptors & Standard Streams\n\nThe operating system provides three default standard streams assigned to specific file descriptors:\n\n\n\n* `0` — **`stdin`** (Standard Input): Default source is Keyboard or input pipes.\n* `1` — **`stdout`** (Standard Output): Default destination is Terminal Console, files, or pipes.\n* `2` — **`stderr`** (Standard Error): Default destination is Terminal Console, files, or pipes.\n* **Difference between `stdout` and `stderr`**:\n * *Convenience*: Allows separating diagnostic error output from pure program data stream.\n * *Urgency*: `stderr` is unbuffered, ensuring error messages print immediately to the display even if the program crashes shortly after.\n\n\n## Unformatted I/O Functions\n\n* Unformatted I/O directly transfers internal binary representations between memory and files without ASCII conversions. It is fast, compact, and efficient.\n* **Standard C Functions (`stdio.h`)**:\n * `getchar()` / `putchar(int ch)`: Reads/writes a single character from/to `stdin`/`stdout`.\n * `getc(FILE *stream)` / `putc(int ch, FILE *stream)`: Macro/function equivalents operating on explicit file streams.\n * `gets(char *str)`: Reads a line from `stdin`. **Extremely dangerous and unsafe**; removed from standard C because it lacks buffer size limits and causes stack-smashing buffer overflows.\n * `puts(const char *str)`: Writes string to `stdout` appending an automatic newline (`\n`).\n * `fgets(char *str, int size, FILE *stream)`: Safe unformatted line input function enforcing array bounds.\n* **Non-Standard Headers (`conio.h`)**: Functions such as `getch()`, `getche()`, and `putch()` belong to MS-DOS `conio.h`. They are non-standard and **not supported** by Unix/Linux C compilers.\n\n\n## Formatted Output: printf() and sprintf()\n\n* Converts internal binary memory representations into ASCII string sequences before printing. Portable and human-readable, but computationally expensive.\n* **`printf()` Prototype**: `int printf(const char *format, ...);`\n * Returns the total number of characters printed on success.\n * `...` denotes **Ellipses**, meaning zero or more optional arguments of any data type can be passed.\n * The number and type of optional arguments must match the format specifiers in the format string.\n* **Format Specifier Anatomy**: `%[flags][width][.precision][length]type_specifier`\n * **Type Specifiers**:\n * `%c`: Single Character\n * `%d` / `%i`: Signed Decimal Integer\n * `%o`: Unsigned Octal Integer\n * `%x` / `%X`: Hexadecimal Integer (lowercase / uppercase)\n * `%u`: Unsigned Decimal Integer\n * `%f` / `%F`: Floating Point (default 6 decimal places)\n * `%e` / `%E`: Scientific Exponential Notation\n * `%g` / `%G`: Shortest representation between `%f` and `%e`\n * `%s`: Null-terminated String\n * **Length Specifiers**:\n * `h`: `short` (`%hX` prints 16-bit hex)\n * `l`: `long` (`%lX` prints 32-bit hex)\n * `ll`: `long long` (`%llX` prints 64-bit hex)\n * `L`: `long double` (`%Lf`)\n * **Width & Precision**:\n * Width (`%5d`): Minimum field width (right-justified, space-padded).\n * Precision (`%.2f`): Rounds floating-point numbers to specified decimal places; for strings (`%.5s`), truncates output to maximum character length.\n * **Flags**:\n * `#`: Alternate form (forces `0x` prefix for `%x`, `0` prefix for `%o`).\n * `-`: Left-aligns output within field width.\n * `0`: Pads leading width with zeros instead of spaces (`%05d`).\n* **`sprintf()`**: `int sprintf(char *str, const char *format, ...);` Writes formatted string output directly into a user-allocated character array buffer instead of standard output.\n\n\n## Formatted Input: scanf() and sscanf()\n\n* **`scanf()` Prototype**: `int scanf(const char *format, ...);`\n * Reads characters from `stdin`, converts ASCII input according to specifiers, and stores values into target addresses.\n * **All arguments following the format string must be explicit pointers/addresses** (`&variable`).\n * Returns the number of successfully matched and assigned input items. Returns `EOF` if input ends or fails prematurely.\n * *Suppression Flag (`%*c`)*: Asterisk suppresses assignment (e.g., `scanf("%d%*c%d", &h, &m);` reads two numbers and discards intervening delimiter character).\n * *Scanset (`%[...]`)*: Restricts matching characters (e.g., `scanf("%[a-z A-Z]", str)` reads alphabetic strings and spaces; `scanf("%[^\n]", str)` reads all characters until a newline is encountered).\n* **`sscanf()`**: `int sscanf(const char *str, const char *format, ...);` Parses and extracts formatted data directly from an existing string buffer.\n\n\n## I/O Buffering Mechanics\n\nTo minimize slow, expensive kernel system calls (`read()`, `write()`), user-space standard I/O libraries buffer data in temporary memory blocks before transferring batches across the user-kernel interface.\n\n* **`stdout` Buffering Triggers**: `stdout` buffer is flushed under five specific conditions:\n 1. Normal program exit/termination.\n 2. Encountering a newline character (`\n`) in formatted output string.\n 3. Executing a reading operation on `stdin`.\n 4. Explicitly calling `fflush(stdout)`.\n 5. When the standard buffer becomes completely full (`BUFSIZ`).\n* **Disabling `stdout` Buffering**: `setbuf(stdout, NULL);` forces immediate unbuffered output.\n* **`stdin` Buffering**: Accumulates input characters until the user presses Enter (`\n`). Trailing newlines left in `stdin` buffer break subsequent character reading loops.\n * *Fixing Stale `stdin` Buffer*: Clear remaining characters using `while(getchar() != '\n');` or `_fpurge(stdin)`.\n* **`stderr` Unbuffered**: `stderr` stream bypasses user-space buffering entirely to display diagnostic error messages instantly.\n\n\n# Strings in C\n\n## Fundamentals, Storage, and Memory Allocation\n\n* **Definition**: A string in C is defined as a contiguous sequence of printable ASCII characters terminated by a null character (`'\n0'`). Double quotes (`"..."`) automatically append an implicit `'\n0'` at the end.\n* **String Literals (Constant Strings)**:\n * Immutable, read-only data stored in the Text/Code segment.\n * String literals are **shared in memory** (literal pooling). Modifying a string literal via pointer (`char *s = "Hello"; s[0] = 'h';`) causes **Undefined Behavior** / Segmentation Fault.\n* **Modifiable Strings**:\n * Character arrays allocated on Stack, Data Segment, or Heap. Elements can be updated freely at runtime (`char s[] = "Hello"; s[0] = 'h';`).\n\n\n## Initialization Forms, Pointers vs Arrays, and String Sharing\n\n* **Initialization Validity Check**:\n * `char str1[6] = {'H', 'E', 'L', 'L', 'O', '\0'};` \rightarrow **Valid** String.\n * `char str2[] = {'H', 'E', 'L', 'L', 'O', '\0'};` \rightarrow6 bytes).\n * `char str3[6] = {"H", "E", "L", "L", "O"};` \rightarrow **Invalid** (assigns string literal addresses to `char` elements).\n * `char str4[6] = {"H" "E" "L" "L" "O"};` \rightarrow **Valid** (concatenates string literals into `"HELLO"`).\n * `char str5[6] = {"HELLO"};` \rightarrow **Valid**.\n * `char str6[6] = "HELLO";` \rightarrow **Valid**.\n * `char str7[] = "HELLO";` \rightarrow **Valid**.\n * `char *str8 = "HELLO";` \rightarrow **Valid** pointer to string literal.\n* **Arrays vs. Pointer Memory Calculations**:\n * `sizeof(char_array)`: Calculates total allocated byte array capacity (`char a[] = "Hello";` \rightarrow 6 bytes).\n * `sizeof(char_pointer)`: Returns constant pointer size (432864-bit systems).\n * An array identifier is a **constant pointer**; it cannot be reassigned to point to a new address (`str2 = "World";` triggers a compilation error). Pointer variables can be reassigned (`str4 = "World";` is valid).\n* **String Sharing Verification**: Comparing addresses of identical string literals (`char *str1 = "Hello"; char *str2 = "Hello"; if(str1 == str2)`) evaluates to true because compilers optimize memory by pointing both pointers to a single read-only pool location.\n\n\n\n\n\n\n## Safe String Input & Common Manipulations\n\n* `gets(str)`: Deprecated and unsafe. Overflowing array length causes stack smashing.\n* `fgets(str, size, stdin)`: Recommended safe function. Stops reading at `size - 1` bytes and automatically appends `'\n0'`.\n* `scanf("%5[^\n]", str)`: Safe alternative reading up to specified width.\n\n\n## String Library Functions Reference\n\nIncluded via header ``:\n\n* `size_t strlen(const char *str)`: Returns character count excluding trailing `'\n0'`.\n* `int strcmp(const char *str1, const char *str2)`: Lexicographically compares two strings. Returns <0>00 if equal.\n* `char *strcpy(char *dest, const char *src)`: Copies source string into destination array. Returns pointer to `dest`.\n* `char *strcat(char *dest, const char *src)`: Appends `src` string to end of `dest` array. Returns pointer to `dest`.\n* `char *strstr(const char *haystack, const char *needle)`: Finds first occurrence of substring `needle` in `haystack`. Returns pointer or `NULL`.\n* `char *strchr(const char *s, int c)`: Finds first occurrence of character `c` in string `s`. Returns pointer or `NULL`.\n* `char *strtok(char *str, const char *delim)`: Tokenizes string into substrings separated by delimiters.\n\n\n# Advanced Pointers and Multidimensional Arrays\n\n## Multilevel Pointers\n\n* A pointer storing the memory address of another pointer variable is a multilevel pointer (`ptr2 \rightarrow ptr1 \rightarrow num`).\n* *Example Trace*:\n ```c\n int num = 10; // Allocated at address 1000\n int *ptr1 = # // Stored at address 2000, value = 1000\n int **ptr2 = &ptr1; // Stored at address 3000, value = 2000\n int ***ptr3 = &ptr2; // Stored at address 4000, value = 3000\n ```\n * `ptr3` \rightarrow Outputs `3000` (Address of `ptr2`)\n * `*ptr3` \rightarrow Outputs `2000` (Address of `ptr1`)\n * `**ptr3` \rightarrow Outputs `1000` (Address of `num`)\n * `***ptr3` \rightarrow Outputs `10` (Value of `num`)\n\n\n\n\n## Array Interpretation and Pointer Arithmetic\n\nFor an array `int a[5] = {1, 2, 3, 4, 5};` residing at base address `1000`:\n\n* `a`: Decays to pointer to first element (`&a[0]`). Value = 1000. Type: `int *`.\n * `a + 1` increments address by 1 \times \text{sizeof}(int) = 1000 + 4 = 1004$.
&a[0]: Explicit address of first element. Value $= 1000$. Type:int *.&a[0] + 1$= 1004$.
&a: Pointer to the entire array block. Value $= 1000$. Type:int (*)[5].&a + 1increments address by full array size 1 \times (5 \times 4) = 1000 + 20 = 1020$.\n\n\n\n\n## Multidimensional Arrays (2D Arrays)\n\n* 2D arrays are stored as a linear, contiguous row-major block in physical system memory.\n* *Element Address Formula*:\n \text{Address}(a[r][c]) = \text{Base Address}(a) + r \times \text{sizeof}(1\text{D Row}) + c \times \text{sizeof}(\text{element})\n* *Decomposition Rule*:\n a[r][c] \equiv ((a + r) + c)\n* **Core Principle of Array Dereferencing**:\n * Dereferencing an n(n-1)-dimensional array pointer.\n * Dereferencing a 2D array (`*a`) yields a 1D row array pointer.\n * Dereferencing a 1D array (`*(*a)`) yields a primitive data element.\n\n\n## Array of Pointers vs Pointer to an Array\n\n* **Array of Pointers**:\n * Syntax: `datatype *ptr_name[SIZE];` (e.g., `int *ptr[3];`).\n * Declares an array holding `SIZE` separate pointer addresses.\n * *Example*: Storing addresses of independent integers or strings (`char *menu[5] = {"File", "Edit", "View", "Insert", "Help"};`).\n* **Pointer to an Array**:\n * Syntax: `datatype (*ptr_name)[SIZE];` (e.g., `int (*ptr)[3];`).\n * Declares a **single pointer variable** pointing to an entire contiguous 1D array block of `SIZE` elements.\n * Pointer arithmetic `ptr + 1` advances memory address by `SIZE * sizeof(datatype)` bytes.\n\n\n## Passing Multidimensional Arrays to Functions\n\n1. **Fixed Syntax**: `void print_array(int p[2][3]);`\n2. **Pointer to Row Array Syntax**: `void print_array(int (*p)[3]);`\n3. **Variable Length Array (VLA) Syntax**: `void print_array(int row, int col, int (*p)[col]);`\n4. **Casted Linear Pointer**: `void print_array(int row, int col, int *p);` accessed inside as `*((p + i * col) + j)`.\n\n\n## 2D Dynamic Array Allocation Patterns\n\nFour structural strategies exist for creating 2D arrays, each with different heap/stack memory overheads:\n\n1. **Both Static (BS - Rectangular Array)**:\n * `int a[2][3] = {{1, 2, 3}, {4, 5, 6}};`\n * Memory: Entirely on Stack.\n * Size Overhead: 2 \times 3 \times \text{sizeof}(\text{int}) = 24 bytes.\n2. **First Static, Second Dynamic (FSSD)**:\n * `int *a[2]; for(i=0; i<2; i++) a[i] = malloc(3 * sizeof(int));`\n * Memory: Array of 2 row pointers on Stack; Columns allocated on Heap.\n * Size Overhead: 2 \times \text{sizeof}(\text{int}) + 2 \times 3 \times \text{sizeof}(\text{int}) = (2 \times 4) + 24 = 32 bytes.\n\n\n\n3. **First Dynamic, Second Static (FDSS)**:\n * `int (*a)[3]; a = malloc(2 * sizeof(int[3]));`\n * Memory: Single pointer on Stack; Entire 2D contiguous array allocated on Heap.\n * Size Overhead: \text{sizeof}(\text{pointer}) + 2 \times 3 \times \text{sizeof}(\text{int}) = 4 + 24 = 28 bytes.\n4. **Both Dynamic (BD - Ragged Array)**:\n * `int **a; a = malloc(2 * sizeof(int*)); for(i=0; i<2; i++) a[i] = malloc(3 * sizeof(int));`\n * Memory: Top pointer on Stack; Row pointer array and column elements allocated on Heap.\n * Size Overhead: \text{sizeof}(\text{int}) + 2 \times \text{sizeof}(\text{int}) + 2 \times 3 \times \text{sizeof}(\text{int}) = 4 + 8 + 24 = 36$$ bytes.