V Lecture 7 — Introduction to C, pointers
* hw2 questions
V C, whirlwind tour
V Java borrowed much of C’s syntax, so a lot of it will be familiar
V same control flow
* if, for, while, switch
* { } denote code blocks
* ; at the end of each statement
V two primary differences
V operations in C are more similar to what the computer is actually doing (compared to Java)
* this is what people mean when they say C is a “lower-level” language
* end result: you have to take care of more things yourself (e.g., memory)
V procedural programming
* no objects, all computation takes place inside functions
V data types
V integer
V char (1 byte), int (4 bytes)
* char is like Java’s byte, usually used to hold ASCII characters
V int can be short or long
* short int = 2 bytes
* long int = 8 bytes
V char and int can be signed (default) or unsigned
* int ranges from -2 billion to +2 billion
* unsigned int ranges from 0 to 4 billion
V exercise: what would char and unsigned char range from?
* -128 to 127, 0 to 255
V floating point
* float (4 bytes), double (8 bytes), long double (16 bytes)
* arrays and structs (more later)
V computer memory
V physical vs virtual
* machines have a finite amount of memory available to running processes
* processes don’t get to manage this themselves
V operating system provides illusion that every process has its own identical chunk of memory
* OS takes care of linking this virtual memory up with the physical memory
* prevents processes from messing up each other’s memory
V each cell of memory has an address
* in virtual memory, addresses always go from 0 to 2^64 (on a 64-bit system)
V exercise: how many bits do we need to represent an address
* an address will take 64 bits
V C pointers
V each piece of data in a C program (or any program) is stored at a specific location in memory
* we say this location is the “address” of that data
* this was true in Java, but in C, we can work directly with these addresses
V a pointer is simply the address of some data
* draw result of int a = 5;
V we can have variables that hold the address of some data
* draw result of int *ptr = &a;
* ptr is the location of a
* *ptr is the value of a (called dereferencing)
V what is the result of int b = *ptr;
* b is now 5
V how about a = a + *ptr;
* a is now 10
V pointers can also be used to modify the data they point to
* *ptr = 8; sets the value of a to 8
V pointers can be reassigned like any variable
V exercise: difference between ptr = &b; and ptr* = b;
* first set ptr to contain the location of b
* second changes the value of what ptr points to to be the value of b
V exercise: does ptr = b; make any sense?
* ptr now points to the memory location 5
* will result in undefined behavior if ptr is dereferenced (probably segmentation fault)
V swap example
* write a function to swap two integers