A full, structured course for first-year computer engineering. It starts with how the machine runs your code, then teaches C in order, from data types and operators through problem solving, functions, pointers, structs, memory and files. Fourteen lectures, Ghana-flavoured examples, and a live console. Open to complete beginners.
C is the language that sits closest to the hardware. To really understand why C behaves the way it does (why 7 / 2 is 3, why a variable has a limit, why scanf needs an &) you need a simple picture of what is going on inside the computer. This first part gives you that picture. You will come back to it in every later topic.
This is also Chapter 1 of your NCE 131 notes, so it doubles as revision for class.
Every computer, from a phone to a server, does the same three things. It takes input, does some processing, and produces output. It also stores data to use later.
Think of a chop bar. Customers give their orders (input). The kitchen cooks (processing). The food is served (output). The storeroom holds ingredients for later (storage). Every part of a computer maps onto one of these jobs.
Inside the machine, every value is held by tiny switches that are either off (0) or on (1). One 0 or 1 is a bit. Eight bits make a byte.
| Unit | Size | Holds |
|---|---|---|
| Bit | 1 switch | 0 or 1 |
| Byte | 8 bits | 256 values (0 to 255), enough for one character like 'A' |
| Word | 16, 32 or 64 bits | what the CPU handles in one go |
| KB / MB / GB | 1024 of the one below | text, photos, whole programs |
With n bits you can make 2 to the power n different values. That is why a byte (8 bits) holds 2^8 = 256 values. This is the reason every C type has a size and a limit.
We count in decimal (base 10, digits 0 to 9). Computers work in binary (base 2, digits 0 and 1). Programmers often write binary as hexadecimal (base 16, digits 0 to 9 then A to F) because one hex digit is exactly four bits.
Each position is worth the base raised to a power. For the binary number 1101:
1101 = 1*8 + 1*4 + 0*2 + 1*1 = 13
In C you write hex with a 0x prefix, so 255 is 0xFF. Memory addresses are almost always shown in hex, like 0x7ffe5a3c.
Decimal to binary: divide by 2 again and again, and read the remainders from bottom to top. For 13:
13 / 2 = 6 r 1 6 / 2 = 3 r 0 3 / 2 = 1 r 1 1 / 2 = 0 r 1 -> read up: 1101
Binary to decimal: add up the place values where there is a 1, as in the slide before. Binary to hex: group the bits in fours from the right and convert each group.
printf("%d", 0xFF);Every microcomputer has four building blocks joined by a shared set of wires called the system bus.
The big idea (the stored-program concept) is that instructions are stored in memory as numbers, just like data. The CPU fetches them one after another and carries them out. This is the fetch, decode, execute cycle: fetch the next instruction, work out what it means, do it, repeat.
People mix these up. RAM is fast working memory that forgets everything when the power goes off. Storage (an SSD or hard disk) is slower but keeps your files when the machine is off.
A program runs in RAM. When you save a file, it goes to storage. You need both: RAM for speed while working, storage to keep things permanently. This is why an unsaved program is lost when the power cuts, something every Ghanaian student knows well.
Two words that sound the same but are not. A microprocessor is only the CPU and needs separate memory and I/O chips. A microcontroller puts the CPU, memory and I/O on one chip, so it is a tiny complete computer.
| Microprocessor | Microcontroller | |
|---|---|---|
| On the chip | CPU only | CPU + memory + I/O |
| Used for | general computing | one dedicated job |
| Examples | Intel Core i5, Apple M-series | ATmega328P (Arduino Uno), ESP32 |
| Found in | laptops, phones, servers | microwaves, cars, Arduino boards |
You write C in a text file ending in .c. The CPU cannot run that text directly. The compiler (gcc) reads your file, checks it, pulls in the library code you asked for, and builds an executable, the real program the machine runs.
C was created in the 1970s and almost everything came after it. Operating systems, other languages, the firmware in your phone, all lean on C. It is strict and honest: it does exactly what you tell it, not what you meant. That is frustrating for a week, and then it makes you a real programmer, because you learn how the machine actually thinks.
Everything in this course is in order. Do not jump ahead. The people who struggle are the ones who skipped the basics and met pointers unprepared.
#include <stdio.h> int main(void) { printf("Hello, Ghana\n"); return 0; }
;. A missing semicolon is the number one beginner error.printf works, Printf does not.{ }.main.Comments explain your code. The compiler skips them. Use them to say why, not just what.
// this is a single line comment /* this is a multi line comment */ int fee = 200; // tuition balance in cedis
Your lecturer requires a comment at the top of every program with your name, index number and what the program does. Get in the habit now.
A variable is a named place in memory that holds a value you can read and change. You make one by writing its type then a name.
int age; // make a box for a whole number age = 19; // put 19 in it double price = 15.50; // make and fill in one line
C is picky about names. A name may use letters, digits and the underscore, but:
2ndScore is invalid)my-name and mtn balance are invalid)float as a name is invalid)age and Age are different boxestotalFee, not x. Your future self and your marker will thank you. This is exactly what Assignment 2 Q1 checks.| Type | Holds | Example | Print with |
|---|---|---|---|
int | whole numbers | 42, -7 | %d |
float | decimals | 3.14 | %f |
double | decimals, more exact | 3.14159 | %lf |
char | one character | 'A' | %c |
For most work you use int and double. Reach for the others when you have a reason.
A char holds one character, written in single quotes like 'A'. Here is the surprise: the computer stores it as a number using the ASCII code. 'A' is really 65, 'a' is 97, '0' is 48.
char grade = 'B'; printf("%c\n", grade); // prints B printf("%d\n", grade); // prints 66, the ASCII code
This is why you can do maths on characters, like 'A' + 1 giving 'B'.
Whole numbers go in an int. Numbers with a decimal point go in a float or a double. A double is the same idea as a float but keeps more digits, so it is more accurate. Prefer double unless you have a reason not to.
By default C prints a lot of decimals. Use %.2f to fix it, where the 2 is the number of places. This matters when printing money.
double price = 15.5; printf("GHS %.2f\n", price); // GHS 15.50 printf("GHS %.0f\n", price); // GHS 16 (rounded, no decimals)
From Chapter 1, every type takes up a fixed number of bytes, and more bytes means a bigger range. The sizeof operator tells you the size on your machine.
printf("int is %zu bytes\n", sizeof(int)); // usually 4 printf("double is %zu bytes\n", sizeof(double)); // usually 8
A 4 byte int holds about plus or minus 2 billion. Go past that and it overflows and wraps around, which is a real bug to watch for with big numbers.
You can stretch or shrink the whole-number types:
long and long long hold bigger whole numbersshort holds smaller ones and saves memoryunsigned drops negatives, so an unsigned int goes from 0 upward only (good for counts and ages)You will not need these often at first, but you will see them in real code and in the notes.
Some values should never change while the program runs, like a fixed fee or pi. Mark them as constants so you cannot change them by accident.
#define BOOKING_FEE 2.00 // no type, no equals, no semicolon const double PI = 3.14159; // the typed way double total = fare + BOOKING_FEE;
Assignment 2 Q5 asks you to use #define for a booking fee. This is why.
When you mix types, C converts them. Mixing an int with a double promotes the int to a double automatically. But divide two ints and you get an int, which loses the fraction.
int bill = 100, people = 3; printf("%d\n", bill / people); // 33, the remainder is lost double share = (double) bill / people; // 33.33, the cast fixes it
Putting (double) in front forces C to treat the value as a decimal before dividing. This is called a type cast, and it is the fix for the integer-division surprise.
A format specifier is a slot in the text that gets replaced by a value. List the values after the text, in order.
int age = 19; double fee = 2450.5; char grade = 'B'; printf("Age: %d, Fee: GHS %.2f, Grade: %c\n", age, fee, grade);
Some characters inside the text are special. They start with a backslash.
| Write | You get |
|---|---|
\n | a new line |
\t | a tab, lines things up in columns |
%% | a real percent sign |
\\ | a real backslash |
So printf("%d%%\n", 75); prints 75% and then a new line.
Combine width and precision to line up a receipt. The \t tab keeps the colons in a column.
printf("Passengers : %d\n", 3); printf("Fare each : GHS %.2f\n", 15.50); printf("Total : GHS %.2f\n", 48.50);
scanf looks like printf with one extra thing: an & before each variable.
int age; printf("Enter your age: "); scanf("%d", &age); printf("You are %d\n", age);
The & means the address of. You are telling scanf where the variable lives in memory (remember memory addresses from Chapter 1) so it can go there and write the value in.
The rule for now: scanf needs an & before each variable, printf does not. You will understand the full story in the Pointers topic. Forgetting the & is one of the most common bugs, and Assignment 2 Q4 has it on purpose.
You can read more than one value at once. For a character after a number, put a space before %c so it skips the leftover Enter key.
int passengers; double fare; scanf("%d %lf", &passengers, &fare); // read an int and a double char grade; scanf(" %c", &grade); // the space before %c matters
%d for int, %lf for double in scanf, %c for char. A mismatch reads garbage.Putting input, a constant, maths and formatted output together.
#include <stdio.h> #define BOOKING_FEE 2.00 int main(void) { int passengers; double fare; printf("Passengers: "); scanf("%d", &passengers); printf("Fare each (GHS): "); scanf("%lf", &fare); double total = passengers * fare + BOOKING_FEE; printf("Total: GHS %.2f\n", total); return 0; }
An expression is any piece of code that works out to a single value, like price + tax. It is built from operands (the values, like price) and operators (the symbols that act on them, like +).
Most operators take two operands, one on each side, like a + b. These are binary operators. A few take one, like the minus in -x. Those are unary. From Chapter 1, it is the CPU's ALU that actually does this work.
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | add | 7 + 2 | 9 |
- | subtract | 7 - 2 | 5 |
* | multiply | 7 * 2 | 14 |
/ | divide | 7 / 2 | 3, not 3.5 |
% | remainder | 7 % 2 | 1 |
Use * for multiply, never x. Writing 3x is an error.
In maths 7 / 2 is 3.5. In C it is 3. The rule: when both operands are whole numbers, C does integer division and throws away the fraction. It does not round, it chops. So 9 / 4 is 2 and 1 / 2 is 0.
int bill = 100, people = 3; printf("Each pays %d\n", bill / people); // 33, the GHS 1 left over is lost
To keep the fraction, at least one value must be a double. Make one a double or cast it with (double), as in the Types topic.
% gives what is left after integer division. 7 % 2 is 1. It only works on whole numbers. It is more useful than it looks:
n % 2 == 0 means n is even4721 % 10 is 1125 / 60 = 2 hours and 125 % 60 = 5 minutesint total = 4000, h, m, s; h = total / 3600; m = (total % 3600) / 60; s = total % 60; printf("%d h %d min %d s\n", h, m, s); // 1 h 6 min 40 s
= stores a value in a variable. The compound operators do an operation and store the result in one step.
int x = 10; x += 5; // x = x + 5 -> 15 x -= 2; // 13 x *= 2; // 26 x %= 5; // 1 (remainder of 26 / 5)
++ adds one, -- takes one away. The position matters. i++ uses the old value then adds one. ++i adds one first, then uses it.
int i = 4; int j = i++ + 2; // uses i as 4, so j = 6, then i becomes 5 printf("%d %d\n", i, j); // 5 6
These compare two values and produce 1 for true or 0 for false.
| Operator | True when |
|---|---|
== | the two are equal |
!= | they are not equal |
< > <= >= | less, greater, less-or-equal, greater-or-equal |
= assigns, == compares. if (x = 5) sets x to 5 and is always true. You almost always want ==.These combine true/false conditions.
&& (and): true only if both sides are true|| (or): true if either side is true! (not): flips true to falseint age = 20, hasID = 1; if (age >= 18 && hasID) { printf("Allowed\n"); }
C does multiply and divide before add and subtract, like in maths. Do not memorise the whole table. Use brackets to make your meaning clear and correct.
int a = 2 + 3 * 4; // 14, the * happens first int b = (2 + 3) * 4; // 20, brackets win
C has no separate true or false by default. 0 means false and any other number means true. So if (count) runs whenever count is not zero. If you want the actual words, include and use bool, true and false.
a / b, a % b, a + b * 2, (a + b) * 2, (double) a / 2, given int a = 7, b = 3;.Storing and printing data is half the job. A program becomes useful when it decides and calculates. The students who struggle usually start typing before they know the steps. So we plan first.
An algorithm is just an ordered list of steps that solves a problem, written in plain language before any C. Three tools help: the IPO table, pseudocode and the flowchart.
Start by asking three questions. What does the program need (input)? What must it do with it (process)? What does it give back (output)?
Example: a final score is 40% of coursework plus 60% of exam. Pass if 50 or more.
| Input | Process | Output |
|---|---|---|
| coursework mark, exam mark | final = 0.4*cw + 0.6*exam; compare to 50 | Pass or Fail |
Pseudocode writes the steps in short English using a few standard words: INPUT, OUTPUT, SET, IF, ELSE, WHILE. No C syntax, no semicolons, just the logic.
START
INPUT coursework, exam
SET final = 0.4 * coursework + 0.6 * exam
IF final >= 50 THEN
OUTPUT "Pass"
ELSE
OUTPUT "Fail"
END IF
ENDA flowchart draws the same logic. Each shape has a fixed meaning, and arrows show the order.
Here is the pass/fail algorithm as a flowchart. Follow the arrows. The diamond is the decision, and the two paths join again at the end.
A trace table (or desk check) means pretending to be the computer and writing down the value of every variable after each line. It finds bugs before you ever compile.
Trace this, following each line:
int n = 5; n += 3; // n = 8 n *= 2; // n = 16 n--; // n = 15 n %= 4; // n = 3
| Line | n |
|---|---|
| int n = 5; | 5 |
| n += 3; | 8 |
| n *= 2; | 16 |
| n--; | 15 |
| n %= 4; | 3 |
Once the pseudocode is right, the C almost writes itself.
#include <stdio.h> int main(void) { double coursework, exam, final; printf("Coursework and exam marks: "); scanf("%lf %lf", &coursework, &exam); final = 0.4 * coursework + 0.6 * exam; if (final >= 50) printf("Pass (%.1f)\n", final); else printf("Fail (%.1f)\n", final); return 0; }
This is Chapter 4 of your notes. Every program ever written, however large, is built from just three patterns of flow.
| Pattern | Means | Everyday example |
|---|---|---|
| Sequence | do steps one after another | wake, bath, dress, go to class |
| Selection | choose steps based on a condition | if it is raining, take an umbrella |
| Repetition | repeat steps while a condition holds | the trotro mate keeps calling Circle while seats are empty |
Chapters 2 and 3 only used sequence. This topic adds selection (decisions). The next adds repetition (loops).
Every decision rests on a condition, a question that is true or false, like balance > 0 or choice == 2. The rule in C: 0 is false, and anything that is not 0 is true. A comparison produces 1 for true and 0 for false.
int age = 20; printf("%d\n", age >= 18); // prints 1 (true) printf("%d\n", age < 18); // prints 0 (false)
An if runs a block only when its condition is true. If it is false, the block is skipped and the program carries on. Here is the classic MoMo low-balance check from your notes.
#include <stdio.h> int main(void) { float balance; printf("Enter your MoMo balance (GHS): "); scanf("%f", &balance); if (balance < 10.0) { printf("Warning: your balance is low.\n"); } printf("Thank you for using MoMo.\n"); return 0; }
Run it both ways. The warning only shows when the balance is under 10, but the thank you always prints, because it sits outside the if block.
A plain if does something or nothing. if-else does one thing when true and a different thing when false. Exactly one block runs, never both. Stack them into an else-if ladder for several bands, like a grader.
int score = 72; if (score >= 80) { printf("A\n"); } else if (score >= 70) { printf("B\n"); } else if (score >= 50) { printf("Pass\n"); } else { printf("Fail\n"); }
When you check one value against a few fixed options, switch is cleaner than a long if chain. Each break stops it. default runs if nothing matched. This is how you build a menu.
#include <stdio.h> int main(void) { int choice; printf("1 Airtime 2 Data 3 Transfer\nChoose: "); scanf("%d", &choice); switch (choice) { case 1: printf("Buying airtime\n"); break; case 2: printf("Buying data\n"); break; case 3: printf("Sending transfer\n"); break; default: printf("Unknown option\n"); } return 0; }
For a quick either/or, the ternary operator is short. Read it as condition ? value-if-true : value-if-false.
int age = 20; char *status = (age >= 18) ? "adult" : "minor"; printf("%s\n", status);
A decision controls one statement. To control several, wrap them in a block with braces { }. A good habit: always use braces, even for one line. It prevents a whole class of bugs. And indent everything inside a block by four spaces. The compiler ignores indentation, but your reader does not, and your course marks down code that is not indented.
= instead of ==; a semicolon right after if (...) which ends the if immediately so the block always runs; missing braces so only the first line is controlled; forgetting break in a switch so cases run together; and comparing decimals with == where tiny rounding makes them unequal.A while loop runs its body again and again, as long as the condition stays true. Something inside must eventually make it false, or it never stops.
int i = 1; while (i <= 5) { printf("%d ", i); i++; // this line ends the loop } // 1 2 3 4 5
A do-while checks the condition at the bottom, so the body always runs at least once. Good for menus and for asking again until the input is valid.
int n; do { printf("Enter a positive number: "); scanf("%d", &n); } while (n <= 0);
A for loop packs the setup, the condition and the step into one line. Use it when you know how many times to repeat.
for (int i = 0; i < 5; i++) { printf("%d ", i); }
break leaves the loop immediately. continue skips to the next pass.
for (int i = 1; i <= 10; i++) { if (i == 5) break; // stop at 5 if (i % 2 == 0) continue; // skip even numbers printf("%d ", i); } // 1 3
Loops can hold loops. This prints a triangle, a classic lab exercise.
for (int row = 1; row <= 4; row++) { for (int col = 1; col <= row; col++) { printf("*"); } printf("\n"); }
<= where you wanted <. And a stray semicolon right after for(...) which makes the body empty.A function is a named block of code that does one job. You run it by writing its name with parentheses. Functions keep programs short, readable, and easy to fix, because the work lives in one place.
int add(int a, int b) { return a + b; } int total = add(3, 4); // total is 7
The values in the parentheses of the definition are parameters, the inputs. return hands a value back to whoever called the function. The int in front of the name is the type of that returned value.
A function that does not return anything uses void as its return type.
C reads top to bottom, so it must know a function before you call it. Either define the function above main, or put a prototype (the first line with a semicolon) above main and the full code below.
#include <stdio.h> int add(int a, int b); // prototype int main(void) { printf("%d\n", add(5, 6)); return 0; } int add(int a, int b) { // definition return a + b; }
A variable made inside a function is local: it exists only inside that function and vanishes when the function ends. That is good, because two functions can both use a variable named i without clashing. A variable declared outside all functions is global and is visible everywhere, but use globals sparingly.
When you pass a variable to a function, C copies it. Changing the copy does not touch your original.
void tryChange(int x) { x = 100; } // only the copy changes int main(void) { int a = 5; tryChange(a); printf("%d\n", a); // still 5 }
To let a function change your variable, pass its address with &. The function takes a pointer. This is how a working swap is written. You will meet pointers fully in the next topic.
void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; } int main(void) { int x = 3, y = 7; swap(&x, &y); printf("%d %d\n", x, y); // 7 3 }
Recursion solves a problem by calling itself on a smaller version. It must have a base case that stops it, or it runs forever and crashes.
int factorial(int n) { if (n <= 1) return 1; // base case return n * factorial(n - 1); // calls itself }
Common maths lives in . Include it and you get square roots, powers and more. On most compilers you link it with -lm when building.
#include <math.h> double r = sqrt(49); // 7.0 double p = pow(2, 10); // 1024.0 double up = ceil(3.1); // 4.0 double dn = floor(3.9); // 3.0
Two advanced ideas you will see later, mentioned so the names are not a surprise. An inline function asks the compiler to paste a tiny function in place for speed. A function pointer stores a function in a variable so you can pass it around, like choosing which operation to run at runtime. You do not need these yet.
int isPrime(int n) that returns 1 if n is prime, else 0.int power(int base, int exp) with a loop, and check it against pow from math.h.An array holds many values of the same type. You reach each one by its index, and indexes start at 0. So a size 5 array has indexes 0 to 4.
int marks[5]; // 5 ints: marks[0] to marks[4] marks[0] = 70; int scores[3] = {90, 80, 75}; // make and fill at once printf("%d\n", scores[1]); // 80
A for loop is the natural way to visit every element, for example to total marks.
int scores[5] = {70, 85, 60, 90, 55}; int total = 0; for (int i = 0; i < 5; i++) { total += scores[i]; } printf("Average: %d\n", total / 5);
marks[5] is out of range (the last valid index is 4). C will not warn you. It reads or writes the wrong memory and causes a bug that is hard to find. Always stay inside the array.A two dimensional array is a table. Good for matrices and seating charts.
int grid[2][3] = { {1, 2, 3}, {4, 5, 6} }; printf("%d\n", grid[1][2]); // 6
A string in C is a char array that ends with a hidden null character '\0'. The word "Hi" is really 'H' 'i' '\0'. That null is how C knows where the text stops.
char name[20] = "Kwame"; printf("%s\n", name); // %s prints a string
scanf("%s", name) reads one word and stops at the first space, so it cannot read a full name with a space. For a whole line, fgets is safer.
char name[30]; printf("Enter your name: "); fgets(name, 30, stdin); // reads the whole line, up to 29 characters
| Function | Does |
|---|---|
strlen(s) | length of the string |
strcpy(a, b) | copy b into a |
strcmp(a, b) | compare, returns 0 if equal |
strcat(a, b) | join b onto the end of a |
== or copy them with =. Use strcmp to compare and strcpy to copy. This catches almost everyone once.Picture memory as a long street of numbered houses. Every variable lives in a house, and each house has an address. A pointer is simply a variable that stores an address instead of a normal value.
That is the whole idea. A pointer does not hold 19, it holds where 19 lives. Everything else about pointers follows from that one sentence.
&x is the address of x. If a pointer p holds that address, then *p is the value sitting there.
int x = 19; int *p = &x; // p holds the address of x printf("%d\n", x); // 19 the value printf("%d\n", *p); // 19 follow p to the value *p = 25; // change x through the pointer printf("%d\n", x); // 25
&.*.This is why pointers matter. Because C copies arguments, a plain function cannot change your variable. Pass the address and it can. This is the working swap from the Functions topic.
void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; } int main(void) { int x = 3, y = 7; swap(&x, &y); // pass the addresses printf("%d %d\n", x, y); // 7 3 }
The name of an array is the address of its first element. So arr acts like &arr[0], and you can step through with pointer maths.
int arr[3] = {10, 20, 30}; printf("%d\n", *arr); // 10, first element printf("%d\n", *(arr + 1)); // 20, next one
A pointer that points nowhere should be set to NULL. If you use a pointer before pointing it somewhere, or you dereference NULL, the program crashes with a segmentation fault. That message means you touched memory you were not allowed to.
NULL, and mixing up p (the address) with *p (the value). Most crashes come from these three.swap(int *a, int *b) and use it.void minMax(int arr[], int n, int *min, int *max) that returns both the smallest and largest through pointers.A struct bundles related values into one unit. Instead of three loose variables for a student, you make one Student that holds all three. Reach a member with a dot.
struct Student { char name[30]; int id; double gpa; }; struct Student s; s.id = 101; s.gpa = 3.8; printf("%d %.1f\n", s.id, s.gpa);
Writing struct Student every time is tiring. typedef lets you write just Student.
typedef struct { char name[30]; int id; double gpa; } Student; Student s; // no need for the word struct s.id = 101;
One struct is a student. An array of structs is the class.
Student class[3]; class[0].id = 1; class[1].id = 2; for (int i = 0; i < 3; i++) { printf("ID: %d\n", class[i].id); }
When you have a pointer to a struct, use -> to reach a member. p->gpa is the short way to write (*p).gpa.
Student s; Student *p = &s; p->id = 55; // same as (*p).id = 55 p->gpa = 3.9;
A member of a struct can be another struct. Here a Date lives inside a Student.
typedef struct { int day, month, year; } Date; typedef struct { char name[30]; Date born; } Student; Student s; s.born.year = 2006; // reach the nested member
A union looks like a struct, but all its members share the same memory, so it holds only one of them at a time. It saves space when a value could be one of several types. You will not need it often, but you should recognise it.
union Value { int i; float f; }; union Value v; v.i = 10; // using it as an int
An enum gives names to a set of related whole numbers, so your code reads in words instead of magic numbers.
enum Day { MON, TUE, WED, THU, FRI }; enum Day today = WED; // WED is really 2 if (today == WED) printf("Midweek\n");
If you check sizeof a struct, it may be bigger than the sum of its members. The compiler adds hidden gaps (padding) so each member sits at an address the CPU reads quickly. It is normal and you rarely need to worry about it, but now it will not surprise you.
Student struct, fill one from user input, and print it back.Variables you declare normally live on the stack: C creates and frees them for you as functions run. When you do not know how much memory you need until the program runs, you ask for it from the heap, and then you must give it back yourself.
malloc asks for a block of memory and gives you a pointer to it. free gives it back. They live in .
#include <stdlib.h> int *nums = malloc(5 * sizeof(int)); // room for 5 ints if (nums == NULL) { return 1; } // always check it worked nums[0] = 10; free(nums); // give it back when done
Related tools: calloc also clears the memory to zero, and realloc resizes a block you already have.
malloc needs a matching free. If you keep asking for memory and never free it, your program slowly eats all the memory and eventually crashes. This is a memory leak, and your course uses tools like Valgrind to catch them.To keep data after the program closes, write it to a file. Open with fopen, giving a mode, and always close with fclose.
| Mode | Means |
|---|---|
"r" | read an existing file |
"w" | write, creating or erasing the file |
"a" | append, adding to the end |
fopen did not return NULL before using the file. It may not exist, or may be locked.FILE *f = fopen("students.txt", "w"); if (f == NULL) { printf("Cannot open file\n"); return 1; } fprintf(f, "Kwame 101 3.8\n"); // like printf, but into the file fclose(f);
FILE *f = fopen("students.txt", "r"); if (f == NULL) { printf("Cannot open file\n"); return 1; } char name[30]; int id; double gpa; fscanf(f, "%s %d %lf", name, &id, &gpa); // read one record printf("%s %d %.1f\n", name, id, gpa); fclose(f);
Type C below and press Run. It compiles with real gcc and shows the output, including the errors. Tap a button to load an example, change it, and run again. Needs an internet connection.
When gcc stops, read the first error, not the last. Fixing the first often clears the rest.
| Message | Meaning | Fix |
|---|---|---|
expected ';' | missing semicolon | add ; at the end of the line above |
undefined reference to main | no main, or misspelled | use int main(void) |
implicit declaration | used a function before declaring it | add the #include or a prototype |
segmentation fault | touched memory you should not | check pointers and array bounds |
format '%d' expects int | wrong specifier for the type | match %d, %lf, %c to the value |
Do these in order, in the console. Try before you look anything up.
When this feels comfortable, the next steps are data structures (linked lists, stacks, queues), which are built on the pointers and structs you now know, and then one of two directions.