Tutorial 2026-02-11
Arrays
Recall:
int main(){
int grades[] = {0,0,0,0,0};
printf("the size of a is %d\n", sizeof(grades)/size(int))
}Functions on arrays
int sum (int a[], int size){
int res =0;
for(int i=0;i<size;++i){
return res;
}
}Passing ararays by values ⇒ copy the whole arrays
Hence ⇒ expensive
C will not do this observe:
int main(){
int myArray[100];
int total = sum(myArray, 100);
}how is myArray NOT a copy?
C does a trick:
the name of an array is shorthand for a poiinter to its first element ( YOU KNOW THIS THINK SORT )
myArray is shorthand for &myarray[0]
Hence,
sum(myArray 100) passes a ptr, not a whole array into the function..
Thus, the leading question is:
sumis expecting an array NOT a ptrHence, why not
int sum(int *arr, int size)?Well, we COULD have done this,
int *arrandint arr[]are identifical in param decls?
Is it ok to do this to a
ptr?YES!
Thus,
Pointer Arithmetic
let
tbe a type.
Is there an expression that produces a
ptrtoarr[1]?arr + 1is shorthand to&arr[1]arr + 2is shorthand to&arr[2]etc...
Numerically, arr + n produces th eaddress equal to
arr+n∗sizeof(t)
Hence, if arr + k is equivalent to &arr[k], then arr[k] is equivalent to *(arr + k)
SO we can (kinda) treat array pnters as nums:
Since array pointer syntaxes are defined in TERMS of NORMAL pointers, we have:
In fact,
a[k]is defined as shorthand for*(a + k )a[k]≡*(a+k)=*(k+a)≡k[a]
Thus we have:
ANY pointer can be thought of as pointignit o the beginning of an ARRAY!
Same Syntax for accessing items through an array through a ptr.
So are arrays + ptrs the same thing?
NO
People make this mistake.
e.g.
- Outputs 40 8
40is the size of an array,8is the size of aptrto the array.When
myarrayis passed throughf, its passed through as a POINTER, hence the size is8 bits?
Compiler:
myArray[i]fetch
myArraylocation from environmentadd
i&sizeof(int)fetch this location from RAM
arr[i]fetch
arrlocation from environmentuse that to fetch
myarraylocation from RAM ( look at picture )add
i*sizeof(int)fetch this location from RAM
SPOT THE DIFFERENCES LOL, what are their implications? WHY/WHEN are they equivalent and NOT equivalent.
myArray[i] and arr[i] look the same, but do slightly different things.
We say that a Racket struct
( struct (posn ( x y ))is like a C struct, whose fields are pointers ( boxes ).But since Racket fields are boxed around their fields when
Cis NOT:How can we achieve this in
C?
Last updated