How does program know array size?

Pages: 12
Hello, I'm learning to code in C++ by reading "Programming principles and Practice using c++ (2nd edition)" by Bjarne Stroustrup. However, decided to clear something up before moving on to the next topic:


I have drawn the vector so as to emphasize that it “knows its size”; that is, a vector doesn’t just store its elements, it also stores its size.

And this one

The subscript operation of vector knows the size of the vector, so it can check.


I couldn't find any useful information while browsing the internet. So the question that comes up is, where is the value of array size stored?

Is memory space allocated for array size?

Last edited on
The snippets you quoted clearly state "vector", not "array". A vector stores its size and capacity in its members. An array doesn't know its own size.
You need to have an extra variable to store the size. Sth. like this:
1
2
3
4
5
6
template<class T>
class Vector
{
  T *data;
  size_t size;
};

When you create your dynamic array you know the size and store it in size;
The implementation details of std::vector are not specified by the C++ standard, it only specifies the interface (which methods it should have) and execution time boundaries.

Most commonly std::vector is implemented using a dynamic array which is resized if you attempt to add more elements than the previous allocation can hold. A typical implementation could contain 3 pointers; one each to keep track of start of array, size of vector and capacity of vector.

https://stackoverflow.com/questions/11893251/stdvector-internals

FYI, the implementation details for the member functions can vary between C++ standard versions.

Re: accessing a vector element...

There are two different methods to access specific elements in a vector, operator[] and .at().

operator[] does no bounds checking. If you try to access an element position that doesn't exist you get undefined behavior.

.at() does bounds checking. Access a nonexistent element an exception is thrown.
on the array and pointer side, the compiler tracks them. I think pointers, it hides it... it allocates a header section that you can't see in front of the pointer (this could just be 1 integer). delete can see it and know what to do. arrays I think it is just tracked at compiler side, while it generates the code, along with other metadata.
Does anyone use std::array instead of the 'normal' array?
Last edited on
@jonnin - std::vector is simply a templated class The variable members of which are private.
The compiler is not doing anything special for a vector. The structure of the private area can be seen by examining <vector.h> or looking at the vector in a debugger.
1
2
3
4
private:
    ValueType *elements;        /* A dynamic array of the elements   */
    int capacity;               /* The allocated size of the array   */
    int count;                  /* The number of elements in use     */


Grey, I prefer using std::array instead of a regular array whenever possible for new code, or updating of old code. No "devolve to ptr" garbage when passing to a function.

I still prefer using std::vector over either fixed sized array types. Less messy creation syntax IMO.

yes, I know what a vector is :)
@The Grey Wolf - depends on the situation. std::array for fixed sized arrays not subject to expansion. std::vector for everything else.
It just struck me, while reading this tread, that I don't really see anyone talk about std::array, it just goes from raw array to std::vector.

I know a lot of people go with the std::vector first approach, which is fine, but would it be fair to say prefer std::array to raw array in a best practice/modern C++ context?

Edit: LeoV3, I just realised that I took this thread off track, sorry about that.
Last edited on
but would it be fair to say prefer std::array to raw array in a best practice/modern C++ context?
When i'm using fixed size arrays it is usually for initialization, i.e. constant. The advantage of raw arrays is that you don't need to specify the size. So in this case I use raw array.

Currently I can't even tell when there was a need to use a non const fixed size array...
I only use std::array when I need or would prefer copy semantics, basically.
When i'm using fixed size arrays it is usually for initialization, i.e. constant. The advantage of raw arrays is that you don't need to specify the size.


You don't need to now. This is valid:

1
2
3
4
5
6
#include <array>

int main()
{
	constexpr std::array myarray {1, 2, 3, 4, 5};
}

std::array is a wonderful tool that isn't needed much.
vector<thing> fixed(size); //does everything std::array does, and can tap additional vector tools if you change your mind on the fixed size.

and I still use raw arrays, because decades of habit if nothing else. I need to get over that, but its hard to remember to do.
@helios - I thought "array" as a general term for a data form that holds the same type elements consecutively. Just don't get used to call it "vector" and "dynamic array". Next time I will try to be more specific

And thank you all for your answers.
vector<thing> fixed(size); //does everything std::array does,


Not quite. std::array can be constexpr (ie compile time initialsied) but std::vector can't be.
I thought "array" as a general term for a data form that holds the same type elements consecutively.
One would usually call that a "sequence".

Just don't get used to call it "vector" and "dynamic array".
A dynamic array is different from both a vector and a plain array (i.e. one whose dynamism is unknown).
I thought "array" as a general term
... it sort of is.
in the context of a language (here, c++) it has language defined meanings. In the context above that, just generic programming talk, your definition is what would be used.
I thought "array" as a general term for a data form that holds the same type elements consecutively.

Generic term for that is "sequence container." There are also "associative" and "unordered associative" containers.

There are also several container adaptors that have different interfaces for sequential containers, usually derived from the deque container.

https://en.cppreference.com/w/cpp/container

While strictly speaking a regular, plain array is not a C++ template container, it does contain a sequential (contiguous) collection of data elements.

coder777 wrote:
The advantage of raw arrays is that you don't need to specify the size.

Since C++17 std::arrays can be initialized with an initializer list, using a deduction guide.
https://en.cppreference.com/w/cpp/container/array/deduction_guides
https://en.cppreference.com/w/cpp/language/class_template_argument_deduction

The deduction guide for std::array means you don't even have to specify the type!

With deduction guides and the common interface the containers library provides using a std::array vs. a plain array is an easier choice IMO.

Pages: 12