Pointers and arrays
- C: Lvalues and Rvalues
- Java: Objects and primitive data types
&— address-of operator*— indirection (or dereference) operator- If
Pis an array of integers, thenPis a constant pointer to an integer. - Pointer arithmetic — The follow rules formally apply only
when the pointers address lvalues within the same array
P[i]is*(P+i).- If
Pis a pointer to an integer, thenP+iis a pointer to thei’th integer after the integer referenced byP. - If
Pis a pointer to an integer, thenP-iis a pointer to thei’th integer before the integer referenced byP. P++incrementspto point to the next integer in memory.P--decrementspto point to the previous integer in memory.
NULLin C is similar tonullin Java.- Pascal had pointers:
@Pfor&PandP^forP*.
It only gets worse
Suppose both P and Q are pointers
to integers.
P+iandP-iandP<QandP>QandP++andP--andP-Qare formally defined only if the relevant pointers are elements of the same array- or the non-allocated location one past the end of the array
P + Qis not allowed for pointersvoid *is the type of a generic pointer* (long *) (void *) &P[5]is weird but implies intent(long) (void *) &P[5]is(long) (void *) P + 5 * sizeof(*P)(long) (void *) &P[5] - (int) (void *) &P[3]is2 * sizeof(*P)
Take a look at the following.
- qsort man page
- illustrative program that may be run at GeeksforGeeks
Trying it out
Take a look at Problem 16 from the Fall 2014 Final exam.