简体   繁体   中英

Difference between array<int, size> name and int name[size]

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 .

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

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM