int * a;
a = new int[10];
cout << sizeof(a)/sizeof(int);
if i would use a normal array the answer would be 10,
alas, the lucky number printed was 1, because sizeof(int) is 4 and iszeof(*int) is 4 too. How do i owercome this? In my case keeping size in memory is a complicated option. How do i get size using code?
My best guess would be to iterate through an array and search for it’s end, and the end is 0, right? Any suggestions?
–edit
well, what i fear about vectors is that it will reallocate while pushing back, well you got the point, i can jus allocate the memory. Hoever i cant change the stucture, the whole code is releevant. Thanks for the answers, i see there’s no way around, so ill just look for a way to store the size in memory.
what i asked whas not what kind of structure to use.
Simple.
Use
std::vector<int>Orstd::array<int, N>(whereNis a compile-time constant).If you know the size of your array at compile time, and it doens’t need to grow at runtime, then use
std::array. Else usestd::vector.These are called sequence-container classes which define a member function called
size()which returns the number of elements in the container. You can use that whenever you need to know the size. 🙂Read the documentation:
When you use
std::vector, you should consider usingreserve()if you’ve some vague idea of the number of elements the container is going to hold. That will give you performance benefit.If you worry about performance of
std::vectorvs raw-arrays, then read the accepted answer here:It explains why the code in the question is slow, which has nothing to do with
std::vectoritself, rather its incorrect usage.If you cannot use either of them, and are forced to use
int*, then I would suggest these two alternatives. Choose whatever suits your need.That is self-explanatory.
The second one is this: allocate memory for one more element and store the size in the first element as: