+ 26
Passing arrays to functions
In the source of this lesson the array and additional the size of the array (number of elements) is passed as a numerical value. I think this can lead to problems when adding more elements to the array and forgetting to correct the number of elements. I think it would be better to calculate the number of elements in an array: void printArray(int arr[], int size) { for(int x=0; x<size; x++) { cout <<arr[x]<< endl; } } int main() { int myArr[3]= {42, 33, 88}; //printArray(myArr, 3); //replace "3" by: printArray(myArr,sizeof(myArr)/sizeof(int)); //<---NEW } what do you think regards lothar
5 Respuestas
+ 11
dear all,
thanks for all your comments. I learned some new thinks.
+ 8
@Lothar, Nice tips mate, I think it's a good idea for such cases, and we can also use sizeof(myArr)/sizeof(myArr[0]) just in case we want to change the type for the array, knowing that explicit use of sizeof(int) will work for the int type only : )
+ 3
Consider std::array instead, that way you don’t have to worry about calculating or keeping track of the size. You can also use templates to have the compiler pass around the size for you, like this: https://code.sololearn.com/c1wqPSpEJnuT/?ref=app
+ 1
This is the way you always have to pass sizes, Lothar . But since you're in C++, std::array (#include <array>) is far better choice, it won't decay to a pointer when passing to a function, therefore you don't need to pass the size as a separate argument in the first place!
Rule: Always prefer std::array, unless you have a strong reason to prefer inbuilt arrays. Happy day! ;)
0
Find two group of number having same average