1

I was going through array using pointers and I found two different dynamic allocation methods of an array

int *ptr_arr=new int[10];

This one was defined in the lectures but when I explored a bit I found a slightly different method:

int **ptr_arr=new *int[10];

Can someone please explain what's the difference between them?

Priyanshu
  • 11
  • 1
  • Do you want 10 `int` or 10 `int*`? `int` is an integer while `int*` is a pointer that can be made to point to an integer. The two are as different as `new int[10]` and `new double[10]`, just the types look a bit similar. – François Andrieux Oct 05 '21 at 13:48
  • The second snippet does not even compile: `new *int[10]` ==> `new int*[10]` – mch Oct 05 '21 at 13:56
  • Pretty much the same difference as between `int arr[10];` and `int* arr[10];`. – molbdnilo Oct 05 '21 at 14:01
  • Basically the expression in general looks like this: `T* ptr = new T[10];`. You are creating a dynamic array of type `T`. What is `T` in both of the examples you have in the question? Maybe that clears things up? – PaulMcKenzie Oct 05 '21 at 14:13
  • @FrançoisAndrieux, @PaulMcKenzie I think I understand now, I am looking to get 10 `int` so the first one gives me a pointer pointing to an array of 10 `int` while the second one gives me 10 `int*` that is int pointers. Did I get it right? – Priyanshu Oct 05 '21 at 14:24
  • 2
    @Priyanshu Seems like you got it right. In practice, use `std::vector if you need a dynamic array of `int`. In general don't use `new` in modern C++. Almost every time you would want to use `new` you can instead use `std::vector` or `std::make_unique`. – François Andrieux Oct 05 '21 at 14:30

0 Answers0