0
#include <iostream>
using namespace std;

int main() {
    int arr[5];
    arr[0]=33;
    arr[1]=47;
    arr[2]=59;
    arr[3]=67;
    arr[4]=98;
    
    for(int i=0;i<5;i++){
        cout<<arr[i]<<endl;
    }

    cout<<endl;

    int two[5]=arr;
    two[2]=590;

    for(int i=0;i<5;i++){
        cout<<two[i]<<endl;
    }
    
    return 0;
}

I was expecting the new array "two" point to the same address as "arr", but instead it gives following error:

array must be initialized with a brace-enclosed initializer
   18 |     int two[5]=arr;
      |                ^~~

I explored that I can use copy() from algorithm header for doing the task. I want to know about other approaches to the same problem.

AyushDwi
  • 7
  • 5
  • 1
    Arrays cannot be assigned or copy initialized from another array. Use `std::array` – Jason Dec 26 '22 at 06:52
  • See [In C++, is it possible to initialize an array directly from another?](https://stackoverflow.com/questions/35030275/in-c-is-it-possible-to-initialize-an-array-directly-from-another) – Jason Dec 26 '22 at 06:54
  • 1
    Arrays haven't changed since the 1970s. They are awesomely simple and feature-limited due to the time in which they were created. It sounds really stupid, but legacy behaviour, especially for program-breaking changes to something as frequently used as an array and with the added weight of the C programming language, doesn't change. – user4581301 Dec 26 '22 at 06:56
  • Don't think that arrays are first class objects. If you do need first class objects then use `std::vector` or `std::array`. – john Dec 26 '22 at 06:59
  • @user4581301 Well "C" arrays may not have changed but C++ did add [`std::array`](https://en.cppreference.com/w/cpp/container/array), which improves handling of arrays a lot. E.g. return from functions, consistent syntax with other object (const, references, copy and move semantics). And importantly not pointer decay and thus loss of size information from the array. All in all I found that code that uses C++ arrays to contain less bugs , specialy for arrays allocated using `new` for which we now have `std::vector`. – Pepijn Kramer Dec 26 '22 at 08:09
  • Remark on code shown : Don't use `using namespace std;` and have a look at [range based for loops](https://en.cppreference.com/w/cpp/language/range-for), these also will help you to avoid out-of-bound bugs (when combined with std::vector/std::array) – Pepijn Kramer Dec 26 '22 at 08:12
  • Changed `int two[5]=arr;` to `int two[5]{arr[0], arr[1], arr[2], arr[3], arr[4]};`. Or use `std::array` or `std::vector`. – Eljay Dec 26 '22 at 13:09

0 Answers0