C Arrays and Pointers for Java programmers
C arrays
- C arrays must be declared in the "older" Java syntax.
- C arrays must be explicitly dimensioned except the last dimention is optional.
double W[5][6][7] ;
double W[5][6][] ;
- C arrays without a last dimension should only be used as fuction parameters where an additional argument gives the size of the last dimension.
double Sum(double A[], int N) ;
- It can be difficult to write generic multi-dimensional C functions.
The following C prototype is illegal in C90.
double Identity(double I[][], int N) ;
-
C arrays are not allocated with
new
.
Generally they are statically allocated on the stack.
-
C arrays can be dynamically be allocated with
calloc
.
This is rarely done.
V = (double *)calloc(1000, sizeof(double)) ;
-
Multidimensional C arrays are not implemented as
arrays of pointer, as in Java. C arrays are stored
in memory in
row major order.
-
C arrays and pointers are highly related.
double Sum(double *A, int N) ;
A[5] == *(A+5) ;
C pointers
- C pointers contain the addresses of C variables.
int *pI;
double *pD;
int *pAI[10];
/* Like a Java 2-D array */
- C pointers are typed, unlike PL/I pointers.
- The address-of operator, &, returns the address of an l-value.
int I = 5 ;
int *pI = I ;
- The dereference (or indirection) operator,
*
, returns the value stored in the l-value referenced by the pointer.
- Arithmetic can be performed on pointers. Adding
i
to
an integer pointer pI
returns the i
'th
integer after pI
.
- Pointers can be compared using C's relational operators.
-
Technically, the C standard only defines the result of adding
to pointers that contain the address of elements within an array.
int i = 5 ;
int A[3] = {1, 2, 3} ;
int *pI = &i ;
int *pA = &A[1] ;
i = *(pA+1) ; /* Sets i to 3 */
i = *(pI+1) ; /* Undefined */
- C increment and decrement operators can also be applied to integers.
&
and *
are unary prefix operators
with a precedence just below that of unary prefix operators.
*++pX == *(++pX) ;
*pX++ == *(pX++) ;
- C arrays are considered constant pointers.
- All Java objects are implemented with pointers.
C array and pointer examples
Barely readable function to reverse an array
void reverse(int V[], int n) {
int i, j ;
for (i=0, j=n-1; i<j; ++i, ++j) {
int t ;
t = V[i] ;
V[i] = V[j] ;
V[j] = t ;
}
}
Unreadable function to reverse an array
reverse(int *p, int *q) {
if (p>q) {
int *t ;
t = p ;
p = q ;
q = t ;
}
for (; p<q; ++p, --q) {
int t ;
t = *p ;
*p = *q ;
*q = t ;
}
}
More unreadable function to reverse an array
reverse(int *p, int *q) {
if (p>q) {
int *t ;
t = p ;
p = q ;
q = t ;
}
while (p<q) }
int t ;
t = *p ;
*p++ = *q ;
*q++ = t ;
}
}
Obscure question from Spring 2008 ECE 209 final
int i, j ;
int m[2] ;
int *p, *q ;
i = 5 ;
j = 6 ;
m[0] = 7 ;
m[1] = 8 ;
p = m ;
q = &i ;
*p = *q ;
printf("%d %d %d %d\n", i, j, m[0], m[1]) ;
p = q ;
*q = j ;
printf("%d %d %d %d\n", i, j, m[0], m[1]) ;