Objective![]()
|
LessonIntroductionPointers refer to memory addresses, as opposed to specific values. They are denoted by the use of an asterisk (*). Consider the following piece of code: int i = 1;
int *k = &i;
int m = i;
printf("i (%p): %d\n", &i, i);
printf("k (%p): %d\n", k, *k);
printf("m (%p): %d\n\n", &m, m);
i++;
printf("i (%p): %d\n", &i, i);
printf("k (%p): %d\n", k, *k);
printf("m (%p): %d\n", &m, m);
/* OUTPUT
i (0x7fff62b5fa54): 1
k (0x7fff62b5fa54): 1
m (0x7fff62b5fa50): 1
i (0x7fff62b5fa54): 2
k (0x7fff62b5fa54): 2
m (0x7fff62b5fa50): 1
*/
In this code, In the brackets can also be seen the memory address of the variable, which shows that
Pointers as Array IteratorsPointers can be incremented, which make them a natural choice for iterating an array. Consider the following piece of code: int a[5] = {0,2,5,8,11};
int *ptr = &a[0];
for (int i = 0; i < 5; i++) {
printf("%p: %d\n", ptr, *ptr);
ptr++;
}
/* OUTPUT
0x7fff645ffa40: 0
0x7fff645ffa44: 2
0x7fff645ffa48: 5
0x7fff645ffa4c: 8
0x7fff645ffa50: 11
*/
Special Application: Linked ListsA linked list is a list of data, comprised of nodes which specify their data, and the address of the next node, or NULL to specify the last node. Consider the following code: #include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node * next;
};
int main() {
struct Node * head = malloc(sizeof(struct Node));
head->data = 0;
struct Node * curr = head;
for (int i = 1; i < 5; i++) {
struct Node * new = malloc(sizeof(struct Node));
new->data = 5*i;
curr->next = new;
curr = curr->next;
}
curr = head;
while (curr != NULL) {
printf("%d\n", curr->data);
curr = curr->next;
}
return 0;
}
In this code, we defined a A linked list is a good visualisation of pointers, but is also an effective data type for Last in First Out structures, such as stacks. Adding to a linked list is simply a matter of creating a new node, and setting its Special Application: Function PointersIn addition to other ways that pointers can be used, they can also reference a function. While this may not seem very useful at first, it can be used to either embed a function in to a struct that uses it exclusively, or to allow a function to return a function or use a function as input to another function. This is a very complex sub-topic and can create a lot of bugs in your program if poorly implemented. |
Assignments![]() |
|