Lab 1
61C Fall 2024
Compiling a C Program
ex1.c
test_ex1.c
gcc
a.out
Running a C Program
Variable Types and Sizes
Guarantee: sizeof(long long) >= sizeof(long) >= sizeof(int) >= sizeof(short)
To know for sure what size your variable is, use uintN_t or intN_t types.
Defining a Function
Specify return type, function name, and function parameters.
int add(int x, int y) { return x + y; }
void nothing() { return; }
Conditionals
if (condition) {� do this;�} else if (condition) {� do this;�} else {� do this;�}
If-else
Switch statements
switch (expression) {
case constant1: � do these;
break;� case constant2:
do these;
break;
default:
do these;�}
Loops
While loop
For loop
while (condition) {
do this;�}
for (int i = 0; i < 10; i++) {
do this;
}
Pointers
100
Address
Data
0xebafb32c
x_ptr
x
&x
int* x_ptr;
int x = 100;
x_ptr = &x;
Address | Data |
… | … |
0x61c0 | 19 |
0x61c4 | 0x61c0 |
0x61c8 | 14 |
… | … |
Memory
x
&x
y
Assigning
int x = 19;
int* y = &x;
might produce something like:
Address | Data |
… | … |
0x61c0 | 19 |
0x61c4 | 0x61c0 |
0x61c8 | 19 |
… | … |
Memory
y
Assigning
(int* y = &x;)
int z = *y;
might produce something like:
z
*y / x
&x
Address | Data |
… | … |
0x61c0 | 20 |
0x61c4 | 0x61c0 |
0x61c8 | 19 |
… | … |
Memory
y
Assigning
(int* y = &x;)
int z = *y;
*y = 20;
might produce something like:
z
*y / x
&x
Address | Binding | Data |
0x61c0 | x | 19 |
0x61c4 | y | 0x61c0 |
0x61c8 | z | 14 |
Name | Value |
x | 19 |
&x | 0x61c0 |
y | 0x61c0 |
*y | 19 |
Address | Binding | Data |
0x61c0 | x | 19 |
0x61c4 | y | 0x61c0 |
0x61c8 | z | 14 |
Name | Value |
x | 19 |
&x | 0x61c0 |
y | 0x61c0 |
*y | 19 |
&x gets the address of the variable x
Address | Binding | Data |
0x61c0 | x | 19 |
0x61c4 | y | 0x61c0 |
0x61c8 | z | 14 |
Name | Value |
x | 19 |
&x | 0x61c0 |
y | 0x61c0 |
*y | 19 |
To create a pointer, we need to declare y to be a pointer type:
int* y = &x;
Address | Binding | Data |
0x61c0 | x | 19 |
0x61c4 | y | 0x61c0 |
0x61c8 | z | 14 |
Name | Value |
x | 19 |
&x | 0x61c0 |
y | 0x61c0 |
*y | 19 |
*y follows the pointer in y, and gets the data stored at that address
Pointers
0xebafb32c
What will this print?
Pointers
0xebafb32c
0xebafb32c
Pointers
0xebafb32c
0xebafb32c
What will this print?
Pointers
0xebafb32c
0xebafb32c
Another address, ex: 0xebafb320
Pointers
0xebafb32c
0xebafb32c
0xebafb320
What will this print?
Pointers
0xebafb32c
0xebafb32c
0xebafb320
22
Pointers
0xebafb32c
0xebafb32c
0xebafb320
22
What will this print?
Pointers
0xebafb32c
0xebafb32c
0xebafb320
22
22
Pointers
0xebafb32c
22
Address
Data
0xebafb330
0xebafb32c
&my_var
my_var_p
&my_var_p
my_var
*my_var_p
&x = address of x
*x = contents at x
Pointers to Structs
Arrow operator
Arrays
Strings
Structs
Structure Tag
Variable declarations
Structs
Dot operator
Structs