Concept
How are arrays passed to functions in C?
ComputerScienceOne / Using Arrays with Functions
"Since arrays are represented using pointers, we can pass and return arrays to and from functions simply by passing in a pointer. When passing an array to a function, we also need to make sure that we communicate to the function the size of the array as there is no reliable way for the function to determine this. By passing both a pointer and an integer representing the size, we are implicitly indicating that we are passing an array and not just a single value. As an example, the following function takes an array of integers and computes their sum.\n\n1 /**\n\n2 * This function computes the sum of elements in the\n\n3 * given array which contains n elements\n\n4 */\n\n5 int computeSum(int *arr, int n) {\n\n6 int i;\n\n7 int sum = 0;\n\n8 for(i=0; i<size; i++) {\n\n9 sum += arr[i];\n\n10 }\n\n11 return sum;\n\n12 }"
Related Ideas
- How do you pass an array of structures to a function to compute an average GPA?ComputerScienceOne · Passing Arrays of Structures
- How do you pass an array of pointers to structures to a function?ComputerScienceOne · Passing Arrays of Structures
- How can recursive functions be written in C?ComputerScienceOne · Recursion
- How can pointer arithmetic and comparators implement a generic getMax()?ComputerScienceOne · Function Pointers
- How can arrays be passed to and returned from methods in Java?ComputerScienceOne · Dynamic Memory
- How do pointers pass values by reference in C?ComputerScienceOne · Function Pointers
- How do you use and validate a dynamically allocated array?ComputerScienceOne · Dynamic Memory
- How can you create an array of strings in C?ComputerScienceOne · Arrays of Strings