0

I found two ways to create an array. What is the difference between them?

  1. array<int, 5> arr = {5, 8, 1, 3, 6};
  2. 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.

John Kugelman
  • 307,513
  • 65
  • 473
  • 519
iromba
  • 35
  • 4
  • Also, what is the using of pointers to find the length when you can just use sizeof()? – iromba Mar 07 '21 at 09:44
  • 1
    Arrays are dumb, `std::array` is smart. That's the difference. Also `int x[1000]; std::cout << sizeof(x);` -- Have you actually tried doing this? Are the results what you expected? – PaulMcKenzie Mar 07 '21 at 10:27
  • 1
    FYI, since C++11, you can use `std::size(arr);` to get the element count of both cases. – Remy Lebeau Mar 07 '21 at 10:49

2 Answers2

2

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

phuclv
  • 27,258
  • 11
  • 104
  • 360
  • Technically, `arr[0]` is specified as being equivalent to an expression using pointers i.e. `*(arr+0)`. – Peter Mar 07 '21 at 10:20
1
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.

Rohan Bari
  • 6,523
  • 3
  • 9
  • 30