How Can I Initialize this Dynamic array?

Hello,

How Can I Initialize this Dynamic array?
I'd like to have pointer to an array with size n
int *arr[n]


1
2
3
4
5
6
7
8
9
10
11
#include<iostream>
using namespace std;


int main() {

    int n;
    cin>>n;
    int *arr[n] = new int*[n];

}
Like so.
1
2
3
4
5
6
7
8
9
10
11
#include<iostream>
using namespace std;


int main() {

    int n;
    cin>>n;
    int *arr = new int[n];

}

Better to use Managed Pointers and unique_ptr:

1
2
3
4
5
6
7
8
9
10
#include <memory>
#include <iostream>

int main() {
	int n;
	std::cin >> n;

	const auto arr { std::make_unique<int[]>(n) };

}


https://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique

You then don't have to have delete[] to free the memory allocated with new []
If you are wanting to have a dynamic array why bother with pointers, even managed/smart pointers. Use what C++ provides, a std::vector. You get a lot of the array semantics, including operator[], and no need to worry about how the memory is managed "under the hood."

https://www.learncpp.com/cpp-tutorial/an-introduction-to-stdvector/

https://en.cppreference.com/w/cpp/container/vector
Topic archived. No new replies allowed.