// Some examples of using pointers
// Marc Chee (cs1511@cse.unsw.edu.au), March 2021
#include <stdio.h>
void increment_int(int n);
void increment_ptr(int *n);
int main(void) {
int i = 100;
// create a pointer called ip that points at i
// it stores the address of i
int *ip = &i;
printf("%p is the address of i, which has the value %d\n", ip, *ip);
increment_int(i);
printf("i, %d, hasn't changed.\n", i);
increment_ptr(ip);
printf("i, %d, has now changed.\n", i);
int numbers[10];
// showing that arrays are actually pointers
// to chunks of memory
printf("%p\n", &numbers[0]);
printf("%p\n", numbers);
}
// This function will have no effect!
// It only modifies it's own variable, n, not the variable in the main
void increment_int(int n) {
n = n + 1;
}
// This function will affect whatever n is pointing at
void increment_ptr(int *n) {
*n = *n + 1;
}
Resource created Wednesday 27 January 2021, 01:16:16 PM, last modified Wednesday 10 March 2021, 02:00:06 PM.
file: pointers.c