Skip to content
LAM
Read Home Blog
Make Projects HTML Tools Games
Touch grass Notes Resume Links
Home Blog HTML Projects
Tools Games Notes Resume Links
Back C Programming Cheat Sheet Programming
Download Open
Show description 1,898 chars · Programming

C Programming Cheat Sheet

C Programming Cheat Sheet










C Programming Cheat Sheet

Structs, Pointers, Memory & File I/O






Structs & Memory Alignment

The size of a struct isn't just the sum of its parts. The compiler adds invisible bytes called **padding** to align members in memory for faster access.


Calculating Struct Size

Consider this struct on a 32-bit system:

struct contact {
char name[30];
int phone;
char email[30];
};


Memory Breakdown


name[30]: 30 bytes

Padding: 2 bytes (to align int on a 4-byte boundary)

phone: 4 bytes

email[30]: 30 bytes

Padding: 2 bytes (to make total size a multiple of 4)


Total Size = 30 + 2 + 4 + 30 + 2 = 68 bytes



Factors that can change a struct's size include:


Computer architecture (32-bit vs. 64-bit).

Adding/removing members.

Changing the order of members.







Pointers & Functions

How you pass variables to functions determines if the original value can be changed.


Pass-by-Value vs. Pass-by-Reference

Pass-by-Value: The function gets a copy of the data. Changes inside the function do not affect the original variable. (Used for y below).

Pass-by-Reference: The function gets the memory address (a pointer) of the data. Changes made via the pointer do affect the original variable. (Used for x below).


// x is passed by reference (a pointer)
// y is passed by value (a copy)
void func(int *x, int y) {
// This changes the ORIGINAL x in main()
*x = *x + y;

// This only changes the LOCAL copy of y
y = 2;
}

void main() {
int x = 10, y = 10;

// Pass the address of x, and a copy of y
func(&x, y);

// Output: x: 20, y: 10
printf("x: %d, y: %d", x, y);
}


Pointer Pitfall!

Inside func, be careful about the difference:


*x = 20; — Changes the value at the original address. (Affects main's x).

x = 20; — Changes where the local pointer `x` is pointing.…

C Programming Cheat Sheet

16,163 bytes · HTML source
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>C Programming Cheat Sheet</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;700&family=Fira+Code:wght@400;500;700&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Inter', sans-serif;
            background-color: #121212;
            color: #E0E0E0;
        }
        h1, h2, h3 {
            font-family: 'Inter', sans-serif;
            font-weight: 700;
        }
        h1 {
            color: #FFA500;
        }
        h2 {
            color: #FFA500;
            border-bottom: 2px solid #FFA500;
            padding-bottom: 8px;
            margin-top: 2rem;
        }
        h3 {
             color: #FF8C00;
        }
        code.inline-code {
            background-color: #2a2a2a;
            color: #FF6347;
            padding: 2px 6px;
            border-radius: 4px;
            font-family: 'Fira Code', monospace;
        }
        pre {
            background-color: #0d0d0d;
            border: 1px solid #333;
            border-radius: 8px;
            padding: 16px;
            overflow-x: auto;
            font-family: 'Fira Code', monospace;
            font-size: 0.9em;
            margin-top: 1rem;
            margin-bottom: 1rem;
        }
        .code-keyword { color: #FF6347; /* Tomato Red */ }
        .code-type { color: #FF8C00; /* Dark Orange */ }
        .code-comment { color: #6A9955; /* Green */ }
        .code-string { color: #CE9178; /* Light Orange */ }
        .code-number { color: #B5CEA8; /* Light Green */ }
        .code-preprocessor { color: #C586C0; /* Purple */ }
        .code-function { color: #DCDCAA; /* Yellow */ }
        .code-variable { color: #9CDCFE; /* Light Blue */ }
        
        .glossary-term {
            color: #FFA500;
            font-weight: 700;
        }
        .glossary-def {
            border-left: 3px solid #FFA500;
            padding-left: 1rem;
            margin-top: 0.5rem;
        }
        .alert {
            background-color: rgba(255, 65, 54, 0.1);
            border-left: 4px solid #FF4136;
            padding: 1rem;
            margin: 1rem 0;
            border-radius: 4px;
        }
        .alert-title {
            font-weight: 700;
            color: #FF4136;
        }
        .info {
            background-color: rgba(255, 165, 0, 0.1);
            border-left: 4px solid #FFA500;
            padding: 1rem;
            margin: 1rem 0;
            border-radius: 4px;
        }
        .info-title {
             font-weight: 700;
             color: #FFA500;
        }
    </style>
</head>
<body class="p-4 sm:p-6 md:p-10">

    <div class="max-w-4xl mx-auto">
        <header class="text-center mb-10">
            <h1 class="text-4xl md:text-5xl font-bold">C Programming Cheat Sheet</h1>
            <p class="text-lg text-gray-400 mt-2">Structs, Pointers, Memory & File I/O</p>
        </header>

        <!-- Section: Structs & Memory -->
        <section>
            <h2>Structs & Memory Alignment</h2>
            <p>The size of a <code class="inline-code">struct</code> isn't just the sum of its parts. The compiler adds invisible bytes called **padding** to align members in memory for faster access.</p>
            
            <h3>Calculating Struct Size</h3>
            <p>Consider this <code class="inline-code">struct</code> on a 32-bit system:</p>
            <pre><code><span class="code-keyword">struct</span> <span class="code-type">contact</span> {
    <span class="code-type">char</span> name[<span class="code-number">30</span>];
    <span class="code-type">int</span>  phone;
    <span class="code-type">char</span> email[<span class="code-number">30</span>];
};</code></pre>

            <div class="info">
                <p class="info-title">Memory Breakdown</p>
                <ul class="list-disc list-inside mt-2">
                    <li><code class="inline-code">name[30]</code>: 30 bytes</li>
                    <li><span class="text-red-400 font-bold">Padding</span>: 2 bytes (to align <code class="inline-code">int</code> on a 4-byte boundary)</li>
                    <li><code class="inline-code">phone</code>: 4 bytes</li>
                    <li><code class="inline-code">email[30]</code>: 30 bytes</li>
                    <li><span class="text-red-400 font-bold">Padding</span>: 2 bytes (to make total size a multiple of 4)</li>
                </ul>
                <p class="mt-2 font-bold">Total Size = 30 + 2 + 4 + 30 + 2 = <span class="text-white">68 bytes</span></p>
            </div>
             <p class="mt-4">Factors that can change a struct's size include:</p>
            <ul class="list-disc list-inside ml-4">
                <li>Computer architecture (32-bit vs. 64-bit).</li>
                <li>Adding/removing members.</li>
                <li>Changing the order of members.</li>
            </ul>
        </section>

        <!-- Section: Pointers & Functions -->
        <section>
            <h2>Pointers & Functions</h2>
            <p>How you pass variables to functions determines if the original value can be changed.</p>
            
            <h3>Pass-by-Value vs. Pass-by-Reference</h3>
            <p><strong class="text-white">Pass-by-Value</strong>: The function gets a <span class="text-orange-400">copy</span> of the data. Changes inside the function do not affect the original variable. (Used for <code class="inline-code">y</code> below).</p>
            <p><strong class="text-white">Pass-by-Reference</strong>: The function gets the <span class="text-orange-400">memory address</span> (a pointer) of the data. Changes made via the pointer <span class="text-red-400 font-bold">do affect</span> the original variable. (Used for <code class="inline-code">x</code> below).</p>
            
            <pre><code><span class="code-comment">// x is passed by reference (a pointer)</span>
<span class="code-comment">// y is passed by value (a copy)</span>
<span class="code-type">void</span> <span class="code-function">func</span>(<span class="code-type">int</span> *<span class="code-variable">x</span>, <span class="code-type">int</span> <span class="code-variable">y</span>) {
    <span class="code-comment">// This changes the ORIGINAL x in main()</span>
    *<span class="code-variable">x</span> = *<span class="code-variable">x</span> + <span class="code-variable">y</span>;

    <span class="code-comment">// This only changes the LOCAL copy of y</span>
    <span class="code-variable">y</span> = <span class="code-number">2</span>;
}

<span class="code-type">void</span> <span class="code-function">main</span>() {
    <span class="code-type">int</span> <span class="code-variable">x</span> = <span class="code-number">10</span>, <span class="code-variable">y</span> = <span class="code-number">10</span>;

    <span class="code-comment">// Pass the address of x, and a copy of y</span>
    <span class="code-function">func</span>(&<span class="code-variable">x</span>, <span class="code-variable">y</span>);

    <span class="code-comment">// Output: x: 20, y: 10</span>
    <span class="code-function">printf</span>(<span class="code-string">"x: %d, y: %d"</span>, <span class="code-variable">x</span>, <span class="code-variable">y</span>);
}</code></pre>
            
            <div class="alert">
                <p class="alert-title">Pointer Pitfall!</p>
                <p>Inside <code class="inline-code">func</code>, be careful about the difference:</p>
                <ul class="list-disc list-inside mt-2">
                   <li><code class="inline-code">*x = 20;</code> &mdash; Changes the value at the original address. (Affects <code class="inline-code">main</code>'s <code class="inline-code">x</code>).</li>
                   <li><code class="inline-code">x = 20;</code> &mdash; Changes where the local pointer `x` is pointing. (Does NOT affect <code class="inline-code">main</code>'s <code class="inline-code">x</code>).</li>
                </ul>
            </div>
        </section>

        <!-- Section: Linked Lists -->
        <section>
            <h2>Linked Lists</h2>
            <p>A data structure where elements (nodes) are linked together using pointers.</p>
            
            <h3>Accessing Nodes</h3>
            <p>Use the arrow operator <code class="inline-code">-></code> to traverse from one node to the next.</p>
            <pre><code><span class="code-comment">// Given a pointer 'head' to the first node...</span>

<span class="code-comment">// Access the name of the 2nd node</span>
<span class="code-variable">head</span>-><span class="code-variable">next</span>-><span class="code-variable">name</span>;

<span class="code-comment">// Access the name of the 3rd node</span>
<span class="code-variable">head</span>-><span class="code-variable">next</span>-><span class="code-variable">next</span>-><span class="code-variable">name</span>;</code></pre>
            
            <h3>Safe Traversal (No Side Effects)</h3>
            <p>To print a list without losing the reference to the start, use a temporary pointer.</p>
            <pre><code><span class="code-type">struct Terminal</span> *<span class="code-variable">temp</span> = <span class="code-variable">head</span>; <span class="code-comment">// Create a copy of the head pointer</span>

<span class="code-comment">// Loop while the CURRENT node is not NULL</span>
<span class="code-keyword">while</span> (<span class="code-variable">temp</span> != <span class="code-keyword">NULL</span>) {
    <span class="code-function">printf</span>(<span class="code-string">"%s"</span>, <span class="code-variable">temp</span>-><span class="code-variable">name</span>);
    <span class="code-variable">temp</span> = <span class="code-variable">temp</span>-><span class="code-variable">next</span>; <span class="code-comment">// Move the temp pointer, not head</span>
}
<span class="code-comment">// After the loop, 'head' still points to the start of the list!</span></code></pre>
            
            <h3>Deleting the First Node</h3>
            <p>A three-step process is required to avoid memory leaks.</p>
            <pre><code><span class="code-type">struct Terminal</span> *<span class="code-variable">temp</span> = <span class="code-variable">head</span>;    <span class="code-comment">// 1. Save a reference to the node to be deleted.</span>
<span class="code-variable">head</span> = <span class="code-variable">head</span>-><span class="code-variable">next</span>;          <span class="code-comment">// 2. Move head to the next node.</span>
<span class="code-function">free</span>(<span class="code-variable">temp</span>);                 <span class="code-comment">// 3. Free the memory of the original first node.</span></code></pre>
        </section>

        <!-- Section: File I/O -->
        <section>
            <h2>File I/O</h2>
            <p>Interacting with files on the disk.</p>
            
            <h3>File Types</h3>
            <p><strong class="text-white">Binary Files</strong>: Store raw bytes, exactly as they are in memory. Most space-efficient and fastest for storing data like arrays of structs.</p>
            <p><strong class="text-white">Text Files</strong>: Store human-readable characters. Less space-efficient due to conversion overhead (e.g., the number `12345` takes 5 bytes as text vs. 4 bytes as a binary `int`).</p>

            <h3>File Operations & Buffering</h3>
            <p>The I/O buffer is a temporary memory space to make file operations faster.</p>
            <ul class="list-decimal list-inside ml-4">
                <li><code class="inline-code">fopen()</code>: Opens a file and **creates the buffer**.</li>
                <li><code class="inline-code">fread() / fwrite()</code>: **Use** the buffer to read/write data in chunks.</li>
                <li><code class="inline-code">fclose()</code>: Flushes any remaining data from the buffer and then **frees the buffer**.</li>
            </ul>

            <h3>Handling Mixed Input</h3>
            <p>Formatted input like <code class="inline-code">scanf()</code> or <code class="inline-code">cin >> var</code> leaves the newline character (`\n`) in the input buffer. This can cause unformatted input functions like <code class="inline-code">gets()</code> or <code class="inline-code">getline()</code> to fail.</p>
            <pre><code><span class="code-type">int</span> <span class="code-variable">age</span>;
<span class="code-function">scanf</span>(<span class="code-string">"%d"</span>, &<span class="code-variable">age</span>);

<span class="code-comment">// FIX: Clear the leftover '\n' from the buffer</span>
<span class="code-comment">// In C:</span>
<span class="code-keyword">while</span>(<span class="code-function">getchar</span>() != <span class="code-string">'\n'</span>);
<span class="code-comment">// In C++:</span>
<span class="code-variable">std</span>::<span class="code-variable">cin</span>.<span class="code-function">ignore</span>(<span class="code-variable">std</span>::<span class="code-variable">numeric_limits</span><<span class="code-variable">std</span>::<span class="code-variable">streamsize</span>>>::max(), <span class="code-string">'\n'</span>);

<span class="code-comment">// Now this will work as expected</span>
<span class="code-function">gets</span>(<span class="code-variable">fullName</span>);</code></pre>
        </section>

        <!-- Section: Glossary -->
        <section class="mb-10">
            <h2>Glossary of Terms</h2>
            <div class="space-y-4">
                <div>
                    <p class="glossary-term">Pointer</p>
                    <p class="glossary-def">A variable that stores the memory address of another variable.</p>
                </div>
                <div>
                    <p class="glossary-term">Dereference</p>
                    <p class="glossary-def">Using the `*` operator on a pointer to access or modify the value stored at the address it's pointing to.</p>
                </div>
                <div>
                    <p class="glossary-term">Memory Alignment</p>
                    <p class="glossary-def">The way data is arranged in memory on specific address boundaries for optimal performance. This is why padding is needed.</p>
                </div>
                 <div>
                    <p class="glossary-term">Padding</p>
                    <p class="glossary-def">Unused bytes added by the compiler inside a struct to ensure its members are properly aligned in memory.</p>
                </div>
                 <div>
                    <p class="glossary-term">Side Effect</p>
                    <p class="glossary-def">A function has a side effect if it modifies some state outside its local environment, like changing a global variable or a variable passed by reference. In our list example, modifying `head` was an unwanted side effect.</p>
                </div>
                 <div>
                    <p class="glossary-term">NULL</p>
                    <p class="glossary-def">A special value used for pointers to indicate that they aren't pointing to any valid memory address. Often represented as 0.</p>
                </div>
                <div>
                    <p class="glossary-term">free()</p>
                    <p class="glossary-def">A standard library function in C used to deallocate memory that was previously allocated with `malloc`, `calloc`, or `realloc`, preventing memory leaks.</p>
                </div>
            </div>
        </section>
    </div>

</body>
</html>