Assigning a value to a dereferenced pointer
- A pointer must have a value before you can dereference it (follow the pointer).
int *x;
*x = 3;Causes error because x does not point to anything
int foo;
int *x;
x = &foo;
*x = 3;Pointers to anything
int *x;
x -> some int
int **y;
y -> some *int -> some int
double *z;
z -> some doublePointers and Arrays
- Array names and pointer variables can be used interchangeably
- You can use the operator with a pointer
int *x;
int a[10];
x = &a[2]; <-- x is "the address of a[2]"
for (int i = 0; i < 3; i++)
x[i]++; <-- x[i] is the same as a[i+2]Pointer arithmetic
- Integer math operations can be used with pointers
- If you increment a pointer, it will be increased by the size of whatever it points to
- Steps though an array of the pointed to type
int *ptr = a;
*ptr *(ptr+2) *(ptr+4)
| | |
V V V
[ ][ ][ ][ ][ ]
a[0] a[1] a[2] a[3] a[4]
int a[5]; Passing pointers as parameters
void swap (int *x, int *y) {
int tmp;
tmp = *x;
*x = *y;
*y = tmp;
}- Pointers are passed by value (the value of a pointer is the address it holds).
- If we change what the pointer points to, the caller will see the change.
- If we change the pointer itself, the caller will not see the change (we get a copy of the pointer).
Memory Allocation
- Memory can be allocated from the heap using malloc
- Must tell malloc how much memory you need
int * ptrToInt;
ptrToInt = malloc(sizeof(int));- When no longer needed, the memory can be freed using free
free(ptrToInt);Dynamic Memory Allocation
- To avoid memory for an object that is size bytes in length:
void *malloc(size_t size);
- To allocate an array of nmemb items, each of which are size bytes in length:
void *calloc(size_t nmemb, size_t size);
- To free previously allocated memory:
void free(void *ptr);
- It is uninitialized
- It is NOT automatically deallocated until the program terminates
- No garbage collection like that found in Java
- Must not be deallocated more than once
- This will result in a difficult to find error