4.3 Examples
Passing Arrays to Functions Using Pointers
When you pass an array to a function, the array is essentially passed as a pointer to its first element. This allows you to modify the array within the function.
Example: Modifying Array Elements in a Function
#include <stdio.h>
void double_elements(int *arr, int size) { for (int i = 0; i < size; i++) { arr[i] *= 2; // Modify the array elements }}
int main() { int arr[] = {1, 2, 3, 4, 5}; int size = sizeof(arr) / sizeof(arr[0]);
printf("Before doubling:\n"); for (int i = 0; i < size; i++) { printf("%d ", arr[i]); }
// Pass the array to the function double_elements(arr, size);
printf("\nAfter doubling:\n"); for (int i = 0; i < size; i++) { printf("%d ", arr[i]); }
return 0;}
Output:
Before doubling:1 2 3 4 5After doubling:2 4 6 8 10
Sample Code 01 (Arrays & Function Pointers)
#include <stdio.h>#include <stdlib.h>#include <string.h>
void print(int *pArr, int len){
int i; printf("Printing the array:\n"); for (i = 0; i < len; i++) { printf("%d ", pArr[i]); } printf("\n");}
int sum(int *pArr, int len){ int i; int total = 0; for (i = 0; i < len; i++) { total += pArr[i]; }
return total;}
int max(int *pArr, int len){ int i; int cur_max = pArr[0]; int cur_max_i; for (i = 0; i < len; i++) { if (pArr[i] > cur_max) cur_max_i = i; }
return cur_max_i;}
/* Create a function pointer type */typedef int (*PtrType)(int*, int);
PtrType ProcessCommandLineArg(char* argv[]){ PtrType fptr; if (strcmp(argv[1], "sum") == 0) { fptr = ∑ /* type => int (*)(int *, int); */ } else if (strcmp(argv[1], "max") == 0) { fptr = &max; }
return fptr;}
int main(int argc, char *argv[]){ /* ./prog sum 10 20 30 40 50 60 */
int i; int len = argc - 2; int *pArr = malloc(sizeof(int) * len);
/* Create a instance with the newly created type */ /* This instance is a function pointer which can poitn to functions like sum and max */ PtrType fptr;
if (argc < 3) { printf("Invalid number of args: usage: <function_name> <arg1> <arg2> <arg3> ...\n"); } else { /* Parse the numbers in the cmd line args into an integer array */ for (i = 2; i < argc; i++) { pArr[i - 2] = atoi(argv[i]); }
fptr = ProcessCommandLineArg(argv); printf("The result is: %d\n", (*fptr)(pArr, len)); }
free(pArr); return 0;}