Reputation: 55
I found two ways to create an array. What is the difference between them?
array<int, 5> arr = {5, 8, 1, 3, 6};
int arr[5] = {5, 8, 1, 3, 6};
I also found that I can use arr.size()
in 1, but I have to use sizeof(arr)/sizeof(*arr)
in 2.
Upvotes: 0
Views: 515
Reputation: 7726
array<int, 5> arr = {5, 8, 1, 3, 6}
This needs to #include <array>
. You're creating an object (of class array
) that accepts template arguments int
and 5
. By using this container, you can have the benefit of the built-in size()
member function.
int arr[5] = {5, 8, 1, 3, 6};
This is a simple C-style array declaration. This is not an object from any class, neither it needs any header to be declared. You need to make your user-defined size()
function. Note that you're trying to get the size of a pointer to integer – sizeof(arr) / sizeof(*arr)
that returns the size of the elements in bytes. You need to use sizeof(arr) / sizeof(arr[0])
instead – so this returns the total number of elements.
Upvotes: 1
Reputation: 41784
TYPE NAME[SIZE]
has always been the way to declare an array and C++ inherited that from C
OTOH std::array
is a new feature in C++11. It's a struct wrapping the old array inside. It has a member named size()
to get the number of elements of the internal array. A plain array doesn't have any methods so obviously you can't get the size that way
what is the using of pointers to find the length when you can just use sizeof()?
sizeof
returns the size in bytes, not the number of elements. And you don't need to use pointers to get the length. sizeof(arr)/sizeof(arr[0])
and sizeof(arr)/sizeof(int)
are 2 common ways to get size, with the latter more prone to error when changing the type of the array
A plain array also decays to pointer so you can't get the size of it inside functions. You must get the size beforehand using sizeof
and pass the size to the function explicitly. std::array
has information about size so the size is known inside functions, but you'll need to write a template to deal with different array sizes which results in multiple implementations of the same function because each instantiation of a templated type is a different type. In this case passing a pointer and size of the array is the better solution
Upvotes: 2