-5
int main()
{
  int *y = new int(5);
  cout << "y = " << y << " &y = " << &y << " *y = " << *y << endl;
  int *p = new int[5];
  cout << "p = " << p << " &p = " << &p << " *p =" << *p << endl;
}

one used [] and another one used (), what's the different and how it works? Can someone help to explain to me? Thanks!

Jason
  • 36,170
  • 5
  • 26
  • 60
Jay
  • 11

2 Answers2

1

You output so many things in your std::cout but most of them don't matter.

try

std::cout << sizeof(int(5)) << " " << sizeof(int[5]) << "\n";

which will output

4 20

since int(5) means a single integer initialised with 5. So sizeof yields the size of an int.

On the other hand, int[5] is what you expect: an array of 5 integers, so sizeof yields 5*sizeof(int).

Two more remarks:

  • creating good old arrays with new definitely is something a beginner should refrain from. If you need dynamically sized indexable storage, use std::vector. There is no speed panalty.
  • refrain from using namespace std; simply type the std::, that makes the code more readable and clearly separates your stuff from library stuff.
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
DrSvanHay
  • 1,170
  • 6
  • 16
  • Help me to deeper understand! – Jay Sep 17 '17 at 02:48
  • "*there is no speed penalty*" - not true. Speed is *slightly* slower with a `std::vector`. `new int[5]` allocates memory but does not fill it. `vector(5)` (or `vector.resize(5)`) allocates memory and zero-initializes it. Also, `operator[]` on a raw pointer is just a simple dereference of the pointer plus an offset, whereas `operator[]` on a `std::vector` is a function call that has to manipulate the call stack. Speed differences are negligible, but they do exist. – Remy Lebeau Sep 17 '17 at 07:39
  • @RemyLebeau The compiler will inline the call to the operator. – DrSvanHay Sep 17 '17 at 15:49
1
int *y = new int(5)

This allocates a single int and sets its value to 5, then assigns y to point at the allocated int.

int *p = new int[5]

This allocates an array of 5 ints, whose values are initially undefined, then assigns p to point at the first int in the allocated array.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770