|
|
|
Lecture 8 — C programs
|
|
|
|
|
get a partner, each draw a picture, explain to your partner
|
|
|
|
|
what memory looks like when swap is called
|
|
|
|
|
void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } int x = 17; int y = 42; swap(&x, &y);
|
|
|
|
|
what memory looks like after these assignments
|
|
|
|
|
int a = 10; int *p = &a; int **s = &p;
|
|
|
|
|
booleans
|
|
|
|
|
no built-in boolean values (no true/false)
|
|
|
|
|
integers are used instead
|
|
|
|
|
0 is false
|
|
|
|
|
any non-zero is true (usually 1)
|
|
|
|
|
arrays in C
|
|
|
|
|
array syntax that you are used to
|
|
|
|
|
int arr[10]; initializes an array of 10 integers
|
|
|
|
|
arr[0], arr[1], …
|
|
|
|
|
except arrays are actually pointers
|
|
|
|
|
arr points to the location of the first element (arr[0])
|
|
|
|
|
arr == &arr[0]
|
|
|
|
|
parr = arr; *parr == arr[0] *(parr + 1) == arr[1] arr[i] == *(arr + i)
|
|
|
|
|
what’s the result of parr++
|
|
|
|
|
parr now points to arr[1]
|
|
|
|
|
pointer arithmetic
|
|
|
|
|
adding an integer i to a pointer p gives you the address for the ith object beyond p
|
|
|
|
|
C strings
|
|
|
|
|
no String objects in C
|
|
|
|
|
a string is represented by an array of characters
|
|
|
|
|
char s[15]; // a string up to 15 characters long
|
|
|
|
|
a char with value 0 is used to mark the end of a string
|
|
|
|
|
called a null terminator
|
|
|
|
|
written '\0'
|
|
|
|
|
string literals are converted into this representation
|
|
|
|
|
"howdy" is actually [‘h’, ‘o’, ‘w’, ‘d’, ‘y’, ‘\0’]
|
|
|
|
|
C programs
|
|
|
|
|
int main(int argc, char **argv)
|
|
|
|
|
argc is the number of arguments
|
|
|
|
|
argv is the argument values
|
|
|
|
|
since we know arrays are points, we can see how char **argv is an array of strings
|
|
|
|
|
pointer to pointer to char
|
|
|
|
|
argv[0] is always the name of the executable
|
|
|
|
|
so for ./gasp arg1 arg2, argv[0] == “./gasp”
|
|
|
|
|
line_count example
|
|
|
|
|
dealing with arguments
|
|
|
|
|
read from file
|
|
|
|
|
#include and #define
|
|
|
|
|
compilation
|
|
|
|
|
gcc -Wall -std=c11 -g -o output_file input_files…
|
|
|