-4

So I have this code in here I've try to create a 2-D array with different sizes, first I declare 3 pointers then I assign different arrays to them and hope it works and it did well, but there is the problem , in the second code the compiler gives an error ( a value of type int* cannot be assigned to an entity type int ) so it means they are no longer pointers I think , but why is that , what am I missing here ? what is the biggest difference in these two codes other than one of them is declared in stack and other is on the heap

int main()
{
   int* arr[3];
   arr[0] = new int[5];
   arr[1] = new int[2];
   arr[2] = new int[6];

  delete[] arr[0];
  delete[] arr[1];
  delete[] arr[2];
}

//2nd Code

int main()
{
   int* arr = new int[3];
   arr[0] = new int[5];
   arr[1] = new int[2];
   arr[2] = new int[6];

}

and sorry for my baddd English

Jarod42
  • 203,559
  • 14
  • 181
  • 302

1 Answers1

1

In the first program there is declared an array of pointers

int* arr[3];

In the second program there is allocated an array of integers

int* arr = new int[3];

So for example the expression

arr[0]

has type int.

If you want to allocate an array of pointers you should write

int ** arr = new int *[3];
    ^^               ^

In this case the expression

arr[0]

has type int * and you may write

arr[0] = new int[5];
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335