Support Board
Date/Time: Wed, 12 Feb 2025 21:20:28 +0000
[User Discussion] - determining length of an array?
View Count: 884
[2020-11-17 07:30:56] |
ycomp - Posts: 321 |
I have a void funcc(int ma[]) {
int len = sizeof(ma)/sizeof(ma[0]); } this won't compile... at least not in my real code which has this in it.. how can I determine the length of an array that is passed to a function? the sizeof code just seems to be how people usually do it in c++, at least that's my impression from googling Date Time Of Last Edit: 2020-11-17 07:31:32
|
[2020-11-17 11:00:48] |
User907968 - Posts: 826 |
The array decays to a pointer when used as a function parameter i.e. you do not pass a copy of the original array, just a pointer to the first element, meaning that sizeof() is not useful here. One method is to pass the length of the array as a function parameter. |
[2020-11-17 11:18:36] |
ycomp - Posts: 321 |
how should I calculate the length of the array before passing it as a parameter? with this sizeof() division method?
|
[2020-11-17 11:44:41] |
User907968 - Posts: 826 |
Where is the array coming from? Are you not already declaring a size when you initialise it in the calling function?
|
[2020-11-17 12:06:15] |
ycomp - Posts: 321 |
i'm just declaring it like this before calling the function that I pass it to int mas[] = { 2,3,4,5,6,7,8,9,10,11,12,13,14,15 };
I have many such arrays of different lengths so there is potential for error later if the code is modified and then length is miscounted and typed in wrongly as a parameter to the function. Currently I do count it visually and pass the length as a parameter but this just feels like really sloppy coding begging for problems in the future. I never realized it would be so hard to determine the length of an array in C++.. is there some standard library functions that can determine the size of any array? if so, how do I call standard library functions? Date Time Of Last Edit: 2020-11-17 12:06:30
|
[2020-11-17 12:47:08] |
User907968 - Posts: 826 |
Ok, I understand now. So you could just use your original method, but do the size calculation is the calling function rather than the callee, or use std::size (https://en.cppreference.com/w/cpp/iterator/size), again, in the calling function. |
To post a message in this thread, you need to log in with your Sierra Chart account: