<aside> 💡 C was designed to give programmers “low-level” access to memory and expose the underlying memory model
</aside>
// This program demonstrates how to use the address operator
#include "cs136.h"
int g = 42;
int main(void) {
printf("the value of g is %d\\n", g);
printf("the address of g is %p\\n", &g);
// to define a pointer, place a star (*) before the identifier
int *pg = &g;
}
Aliasing occurs when the same memory address can be accessed from more than one pointer variable
// read_sum() reads ints from input (until failure)
// and returns their sum
// effects: read input
int read_sum(void) {
int sum = 0;
int n = 0;
while (scanf("%d", &n) == 1) {
sum += n;
}
return sum;
}
Use scanf(” %c”, &c) to omit whitespace
Const pointers
*int p; | p can point at any mutable integer, you can modify the int (via *p) |
---|---|
*const int p; | p can point at any integer, you can NOT modify the integer (via *p) |
int * const p = &i; | p always points at the integer i, i must be mutable and can be modified |
const int * const p = &i; | p always points at the integer i, you can not modify i (via *p) |
As a recap, we now have a fourth side effect that a function may have:
(Make sure you remember do document them during the exam!)
https://online.cs.uwaterloo.ca/assets/courseware/v1/38297a5bb5b49d85c7a18e0cc4acca70/asset-v1:UW+CS136+2023_01+type@asset+block/04-pointers-show.pdf