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