Pointers - Arithmetic and Function Pointers
Arrays & Pointers
Arrays are a sugar for pointer arithmetic. We can emulate this behaviour like so:
#include <stdio.h>
int main()j {
int i;
int arr[5] = {1, 2, 3, 4, 5};
int *p = arr;
for (i = 0; i < 5; i++) {
printf("%d\n", *p);
p++;
}
}
This prints out the first 4 elements of the array.
Pointer Arithmetic
When adding or subtracting to a pointer like so:
int *p = arr;
p++;
the value added is multiplied by the size of the type.
Hence 4 would be added to the pointer here to account for the size of int
.
Size of Pointer
A pointer to a type always has a size of 8 bytes on a 64 bit machine:
sizeof(int) is 4
sizeof(char) is 1
sizeof(float) is 4
sizeof(double) is 8
==========
sizeof(int*) is 8
sizeof(char*) is 8
sizeof(float*) is 8
sizeof(double*) is 8
Pointers with Functions
Pointers as Function Arguments
- A pointer as a function parameter is used to hold the addresses of arguments passes during a function call (call by reference).
- When a function parameter is called by reference any change made to the reference variable will affect the original variable.
Functions Returning Pointer Variables
A function can return a pointer to the calling function.
- Local variables of a function don’t live outside of the function.
Pointers to Functions
A pointer to a function can be used as an argument in another function.
To declare a pointer to a function:
type (*pointer-name)(parameter);
We can use this like so:
int (*s)(); // s is a pointer to a function with no parameters
// it returns an int
We can then assign this to another function:
s = sum; // assign s to sum function
Passing the Pointer to Another Function
We can then use this, to use a function in another function:
#include <stdio.h>
int sum(int x, int y) {
return x + y;
}
// This function takes a function that returns an int:
int sum6_9(int (*fp2)(int,int)){
return (*fp2)(6, 9);
}
int main() {
int (*fp)(int, int)
fp = sum;
printf("Sum is %d.\n", sum6_9(fp));
return 0;
}
Using Function Pointers in Return Values
We can also have a function that houses many functions:
#include <stdio.h>
int sum(int x, int y) {
return x + y;
}
int (*functionFactory(int z))(int, int) {
printf("Got parameter %d.\n", z);
int (*fp)(int,int) = sum;
return fp;
}
int main() {
printf("Sum is %d.\n", functionFactory(3)(6,9));
return 0;
}