From 68765e02ac949e857a9f467f7ebf988342395348 Mon Sep 17 00:00:00 2001 From: h1110050 Date: Sun, 27 Oct 2019 21:39:29 +0800 Subject: [PATCH] An example of how to use pointers in functions in C --- pointer_functions.c | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 pointer_functions.c diff --git a/pointer_functions.c b/pointer_functions.c new file mode 100644 index 0000000..5666966 --- /dev/null +++ b/pointer_functions.c @@ -0,0 +1,30 @@ +/* This program swaps values by passing variables as pointers into a function in C. + * Author: h1110050 + * Profile: http://github.com/h1110050 + */ + +#include + +void swap(int *, int *); + +int main(void) { + int a = 1, b = 3; + + printf("a is %d, b is %d\n", a, b); + + // Pass in the address if you want the change to persist in main function. + swap(&a, &b); + + printf("a is %d, b is %d\n", a, b); + + return 0; +} + +void swap(int *a, int *b) { + int temp; + + // Swap the pointers. + temp = *a; + *a = *b; + *b = temp; +} \ No newline at end of file