Check max size of array

Hello, I have question. In my simple code. I have some array any type. For exaple: char MyArray[55].
I passing MyArray into function FillArray. Now My function has to know max size of array. Is it possible read max size of MyArray in function FillArray?



1
2
3
4
5
6
7
8
9
10
11
void FillArray(char *array)
{
//How to read max size of array in this place?
}

int main()
{
char MyArray[55];
FillArray(MyArray);
return 0;
}
Pass it from parameter, I think that's the only way you can't use sizeof(array)/sizeof(array[0]) in another function
No, it is not possible, as C-style array are old and do not know their own size (+ they have otherserious problems, but it is too earl to try to understand them for you).

As LendraDwi said, pass size as second argument. However consider to not use C-arrays at all, C++ provides replacements for every potential use of C-array.
It is easily possible, though.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void FillArray(char *array, size_t size)
{
  for (size_t n = 0; n < size; n++) array[n] = whatever;
}

template <size_t Size>
inline
void FillArray(char (&array)[ Size ])
{
  return FillArray(array, Size);
}

int main()
{
  char MyArray[55];
  FillArray(MyArray);
}

Keep in mind, that only works when you have the original, actual array type. You could get the same information this way:

1
2
3
4
5
6
#include <iterator>

int main()
{
  char MyArray[55];
  FillArray(MyArray, end(MyArray)-begin(MyArray));

But if you are going to use iterators, you might as well use them directly:

1
2
3
4
5
6
7
8
9
10
void FillArray(char *first, char *last)
{
  while (first != last) *first++ = whatever;
}

int main()
{
  char MyArray[55];
  FillArray(begin(MyArray), end(MyArray));
}

etc.

Hope this helps.
Thanks guys. I understood that I have to pass 2nd argument. I analyze what way will be better for me.
Topic archived. No new replies allowed.