Some resource materials
- C for Java Programmers at Cornell
- C for Java Programmers at Columbia
- The Basics of C Programming at HowStuffWorks
- My ECE 209 notes
Picturing pointers
Let’s draw Problem 6 (page 5) of a final exam from two years ago.
Quotes from the first printing (in Taiwan) of K & R (Kerninghan and Ritchie)
Pointers
- An object is a manipulatable region of storage; an lvalue is an expression refering to an object. (p. 183)
- A pointer to an object in an array and a value of any integral type may be added. That latter is in all cases converted to an address offset by multiplying it by the length of the object to which the pointer points. (p. 188)
- If two pointers to objects of the same type are subtracted,
the result is converted (by division by the length of the object)
to an
int
representing the number of objects separating the pointed-to objects. (p. 189) - Two pointers may be compared; the result depends on the relative location in the address space of the pointed-to objects. Pointer comparison is portable only when the pointers point to objects in the same array. (p. 189)
Order of evaluation
- The order of evaluation is not specified for associative and
commutative operators like
*
and+
; (p. 73) - C, like most languages, does not specify in what order the operands of an operator are evaluated. (p. 49)
- Simlarly, the order in which function arguments are evaluated in not specified, (p. 50)
- One unhappy situation is typified by the statement
a[i] = i++ ;
(p. 50)
Miscellaneous
- if either operand is
unsigned
, the other is converted tounsigned
and that is the type of the result, (p. 184) - The expression
E1[E2]
is identical (by definition) to*((E1)+(E2))
. (p. 186) - Thus the expression
E1->MOS
is the same as(*E1)->MOS
. (p. 186)
Problems with variables
- In pre-C99 C, variables must be declared at the beginning of a block
- The function parameter list is considered a block
- Variables cannot be declared in a
for
- variable scope
- local variables are not initialized
- C data types
- integers
- Size can be unpredictable
- Signed and unsigned
- Type promotion: signed numbers are promoted to unsigned
-5 < 5U
- C99 data types —
inttypes.h
- booleans
- declarations can be confusing
int *px[100] ;
int (*pa)[100] ;
sizeof px
is100 * sizeof(int *)
sizeof px
is100 * sizeof px[0]
sizeof pa
issizeof(int **)
sizeof pa
issizeof(int (*)[100])
- arrays are stored in
row-major order
int [202][255] x ;
&x[49][64] + 202
is&x[50][64]
&x[49][254] + 1
is&x[50][0]
x[100]
is a one dimentional arrayx
is of typeint (*)[100]
- not
int **
- not the illegal
int[][]
- not
- integers
- C operator precedence —
[]
before prefix*
*px[50] = 255 ;
(*pa)[50] = 255 ;
Common C usages from last and next labs
- Structure definitions
- Used more than Java classes
- Large structures are often passed by pointer
- with the
const
modifier - just like in Pascal
- with the
- Structure access via
->
and.
- Function prototypes
- Always use them