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

size is NOT part of the type, this works on arrays of ANY size !
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:

  • sum is expecting an array NOT a ptr

    • Hence, why not int sum(int *arr, int size) ?

      • Well, we COULD have done this,

        • int *arr and int arr[] are identifical in param decls?

  • Is it ok to do this to a ptr?

    • YES!

Thus,

Pointer Arithmetic

  • let t be a type.

  • Is there an expression that produces a ptr to arr[1]?

    • arr + 1 is shorthand to &arr[1]

    • arr + 2 is shorthand to &arr[2]

    • etc...

  • Numerically, arr + n produces th eaddress equal to

arr+nsizeof(t)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:

circle-info
  • 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

triangle-exclamation

e.g.

- Outputs 40 8

  • 40 is the size of an array,

  • 8 is the size of a ptr to the array.

    • When myarray is passed through f , its passed through as a POINTER, hence the size is 8 bits?

Drawing
  • Compiler:

  • myArray[i]

    • fetch myArray location from environment

    • add i&sizeof(int)

    • fetch this location from RAM

  • arr[i]

    • fetch arr location from environment

    • use that to fetch myarray location from RAM ( look at picture )

    • add i*sizeof(int)

    • fetch this location from RAM

circle-info

SPOT THE DIFFERENCES LOL, what are their implications? WHY/WHEN are they equivalent and NOT equivalent.

circle-info

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 C is NOT:

    • How can we achieve this in C?

Last updated