-1

What is the different between the following two lines of code in C++?

Line1:

MyClass ** objects = new MyClass * [Number];

Line2

MyClass *  objects [Number];
Admia
  • 1,025
  • 3
  • 12
  • 24
  • 1
    you sure this is c++? – BufBills Dec 07 '16 at 20:08
  • @BufBills Why wouldn't it be? – melpomene Dec 07 '16 at 20:10
  • 2
    This is a general-reference question. Consult [your favorite book on the C++ language](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) to see what the `new` operator does, how objects are allocated with automatic storage duration, and how pointers work. – Cody Gray - on strike Dec 07 '16 at 20:11
  • 1
    Same as the difference between `int foo[10];` and `int *foo = new int[10];`. – melpomene Dec 07 '16 at 20:12
  • 1
    The first creates a *dynamic* array of pointers from the *free store* (heap), the second creates an array of pointers as a local *automatic* variable (on the stack) that will be deleted automatically when it goes out of scope. – Galik Dec 07 '16 at 20:16
  • So *(objects+2) for Line 1 is equivalent to objects[2] for Line 2? – Admia Dec 07 '16 at 20:28
  • 1
    `*(objects+2)` is equivalent to `objects[2]` for *both* of them. The access syntax is the same for both. – Galik Dec 07 '16 at 21:13

1 Answers1

1

The line1 defines a pointer to pointer to object and it contains initializer. The second line (line2) defines an array of pointers to objects. This array is not initialized in any way.

Kirill Kobelev
  • 10,252
  • 6
  • 30
  • 51
  • By initializing you mean giving some initial values to the objects? – Admia Dec 07 '16 at 20:26
  • 1
    No, not to the MyClass objects. In Line1 your variable `objects` after initialization starts to point to a number of pointers (array of pointres). And elements of this array are not initialized. – Kirill Kobelev Dec 07 '16 at 20:30