+ 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

19th Feb 2018, 4:25 PM
Lothar
Lothar - avatar
5 ответов
+ 11
dear all, thanks for all your comments. I learned some new thinks.
21st Feb 2018, 6:21 PM
Lothar
Lothar - avatar
+ 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 : )
19th Feb 2018, 4:40 PM
Ipang
+ 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
19th Feb 2018, 7:35 PM
aklex
aklex - avatar
+ 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! ;)
29th Jul 2021, 1:32 AM
Rishi
Rishi - avatar
0
Find two group of number having same average
3rd Oct 2020, 1:35 PM
S.Dayakar Reddy