đŸ§„

Pointers/Arrays/Pointer Arithmetic

TypeQuiz 4 Material

Notes

Pointers

Pointers are variables that contain a memory address

* is the symbol for pointer type

& is the “address of” operator; you use it to obtain a pointer to an existing data item, used in place of object references

An & symbol can be used to find the address of a code element such as a variable or function, and then assigned to a pointer:

char *x;   // declares that x is a pointer to a char.
char **y;  // declares that y is a pointer to a pointer to a char.
void *z;   // declares that z is a pointer to an unspecified type

char i = 97;    // i stores the value 97 or 'a'
char *x = &i;   // x stores the address of the variable i
char **y = &x;  // y stores the address of the variable x
void *z = &i;   // z also stores the address of the variable i

To reference what a pointer points to, we use the dereference operator * (acts like “indirect” in LC-3 loads and stores)

Pointer Declaration:
int i, x;
int *px = &x;
Declaration: *px —> pointer to px

Pointer Expression:
i = *px;
Expression: get the data px points to

Dereferencing a Pointer

int y = 7; 
int *x = &y;
R0 = *x;
R0++;
*x = R0;// C can’t directly modify registers like this, but this is C pseudocode  ̄\_(ツ)_/ ̄

//One possible assembly implementation:
.orig x3000
LDI R0, X      ; R0 = mem[mem[x3021]]
ADD R0, R0, 1  ; R0++;
STI R0, X      ; mem[mem[x3021]] = R0;
.end
.orig x3020
X .fill x3021
Y .fill 7      ; address x3021
.end

Pointers and Arrays

Arrays in c (like in assembly) is a fixed-size sequence of same-typed elements

int arr[5];                // declares arr as an array of 5 ints
char arr[] = {'A',66,'C'}; // arr is an array of 3 chars
int *arr[3]; // arr is an array of 3 int pointers

int a[10]; —> a is an array, size 10, of int

int *p; —> p is a pointer to int (memory address)

In an expression, an array name becomes a constant pointer to the first element


Arrays can decay to pointers to their first element. And you can treat a pointer like an array since array notation is a shorthand for pointer arithmetic

int *ptr;
int arr[10];
*(ptr + x) == ptr[x];
*(arr + x) == arr[x];

Strings and Pointers

Strings in C are accessed through a pointer to the first character

C-strings are null-terminated (just like in assembly)

char *a;   //denotes a pointer to a character
char *a = "Hello";  // null terminator is added implicitly
char b[] = {'W', 'o', 'r', 'l', 'd', '\0'};

char str[6] = “Hello”;

char *str; —> pointer to the first character of str

Pointer Arithmetic

Adding and subtracting to/from pointers; it adds offset times the size of the pointer type.

int *p = &i;

p = p + 1; —> is interpreted as p = p + 1 * sizeof(*p);

(if p is an int pointer, p + 1 is the address of the next int – the address in p is incremented by the size of an int)

int *y;
y + 2 evaluates to y + 2*sizeof(int)
y[2] (array notation) is an equivalent shorthand

int arr[4];

arr[3] = 12; is equivalent to
*(arr + 3) = 12; is equivalent to
arr + 3*sizeof(int)

This also applies to arrays:

  1. int arr[4];
  1. arr[3] = 12;
  1. *(arr + 3) = 12

Pointers to Structs

—> Operator

The left operand must be a pointer to struct and the right operand a struct member

A shorthand for *

Implementing a call-by-reference function with pointers

SWAP function

No pointers(bad!)

Arrays

Find the dimension of an Array IN SCOPE(not a parameter):

sizeof(ary) / sizeof(ary[0])

If the array is passed as a parameter:

Must pass the length with the array

Initializing Arrays

Use values in braces "{}"

int ib[5] = {5,4,3,2,1};

or:

int ib[] = {5,4,3,2,1,0};

or

char cb[] = {'x', 'y', 'z'};

or

char cb[] = "hello"; —> cb: h e l l o \0, size = 6

or

char *cb = "hello"; —> pointer to the address that contains "hello", size is the size of the memory address

Array as arguments

char s[10] = “Hello”;

void test(char *s) {

printf(“%s\n”, s);

}

int main(int argc, char *argv[]) {

test(s);

test(&s[0]);

}

To pass an array into a function, we pass a pointer to the first element.

Note that an array name in an expression (function call) is automatically promoted to a pointer to its first element.

This includes strings (arrays of char)

Sizeof()

Questions & Answers

Practice question: Assume we're on a machine where sizeof(int) = 4 and sizeof(int *) = 4. Given

int c[3];

Which of the following are equivalent to c[1]? There may be more than one correct answer.

Practice question: Assume we're on a machine where sizeof(int) = 4. What would the following program print?

int main(void) {
  struct coord {
    int x; // 0x4 bytes
    int y; // 0x4 bytes
  };
  struct coord coords[10];  // assume this starts at address 0x4000
  printf("%p\n", &coords[4].y);
}