I have a variable of type float[] in C++. The variable is defined in a third-party header file and accessible from my source code. Can I get the size of the variable at run-time?
Asked
Active
Viewed 71 times
-2
-
2Absolutely no.. – iBug Mar 13 '18 at 16:26
-
3If it *is* an actual array, and not a pointer, then yes. – Some programmer dude Mar 13 '18 at 16:26
-
3I am not the downvoter. But if the third party library expects you to use the array, then they should let you know the size of the array at the compile time. – VHS Mar 13 '18 at 16:26
-
Why not std::vector if it's C++? – iBug Mar 13 '18 at 16:27
-
3can you show code where you try to do this. Its not clear exactly what type you are talking about – pm100 Mar 13 '18 at 16:28
-
@iBug: Huh? Why not? – Lightness Races in Orbit Mar 13 '18 at 17:01
-
Exercise caution with that duplicate, as its accepted answer does not sufficiently emphasise that you should be using one the template solution given in the other answers. Still, it's the same question. – Lightness Races in Orbit Mar 13 '18 at 17:02
1 Answers
0
If this array was not allocated dynamically, you can do this
int size=sizeof(array)/sizeof(array[0])
This will not work if you are using an array created dynamically.

Gatchan00
- 11
- 2
-
5Close. This will not work if the array has _decayed to a pointer_. That happens rather frequently, even when the array is not created dynamically. – Drew Dormann Mar 13 '18 at 16:34
-
Worse, it will fail silently, giving you the wrong answer. – Lightness Races in Orbit Mar 13 '18 at 17:01