This chapter is from the book
Passing Pointers to Functions
When you pass a pointer to a function, that function can use the pointer to change data in the calling code. For instance, here’s an example that passes a pointer to a function that changes a variable:
int data = 1; int* datapointer = &data; printf("Before changer(), data = %i\n", data); changer(datapointer); printf("After changer(), data = %i\n", data); void changer(int* pointer) { *pointer = 2; }
To pass a pointer to a function:
- Create a new program named functionpasspointers.m.
- In functionpasspointers.m, enter the code shown in Listing 4.11.
This code passes a pointer to a function named changer().
Listing 4.11. Starting functionpasspointers.m.
#include <stdio.h> void changer(int*); int main() { int data = 1; int* datapointer = &data; printf("Before changer(), data = %i\n", data); changer(datapointer); printf("After changer(), data = %i\n", data); return 0; } . . .
Listing 4.12. The functionpasspointers.m program.
#include <stdio.h> void changer(int*); int main() { int data = 1; int* datapointer = &data; printf("Before changer(), data = %i\n", data); changer(datapointer); printf("After changer(), data = %i\n", data); return 0; } void changer(int* pointer) { *pointer = 2; }
- Add the code for the changer() function, which changes the data back in the calling code (Listing 4.12).
- Save functionpasspointers.m.
- Run the functionpasspointers.m program.
You should see the following:
Before changer(), data = 1 After changer(), data = 2