Last active
April 27, 2020 04:36
-
-
Save joshwiens/f0d7ea64ff4c58bcb96dc3b1bdca52ee to your computer and use it in GitHub Desktop.
Passing an array to a function in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
// Declare function: In this case, returns the average of the intigers contained in the array | |
double returnAverage(int arr[], int size) | |
{ | |
int i, sum = 0; | |
double avg; | |
for (i = 0; i < size; ++i) | |
{ | |
sum += arr[i]; | |
} | |
avg = double(sum) / size; | |
return avg; | |
} | |
int main() | |
{ | |
// an int array with 5 elements. | |
int intArray[5] = {1230, 14, 25, 17, 342}; | |
double avg; | |
// Pass a pointer of the array to the function as an argument (this is the concept you are having trouble with). | |
// (intArray, 5) is no different than (intArray[5]) In this case, it's always treated as a pointer. | |
avg = returnAverage(intArray, 5); | |
// Output the average value | |
cout << "Average value is: " << avg << endl; | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For Multi-Dimensional arrays, passing the array by reference without losing the dimension information is generally accepted | |
// assuming you know the dimensionality of the array at compile time. | |
template <size_t size_x, size_t size_y> | |
void func(double (&arr)[size_x][size_y]) | |
{ | |
printf("%p\n", &arr); | |
} | |
int main() | |
{ | |
double a1[10][10]; | |
double a2[5][5]; | |
printf("%p\n%p\n\n", &a1, &a2); | |
func(a1); | |
func(a2); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment