-1

I know that “int *a = new int” is used to allocate memory to contain one single element of type int. The “int *a = new int [5]" is used to allocate a block (an array) of elements of type int. But when I run this code

int *a=new int;
for(int i=0;i<4;i++)
   a[i]=i;
for(int i=0;i<4;i++)
   cout<<a[i]<<endl;

It runs without any error, and shows the correct output, so when should I use "int *a=new int [5]"? Or are they both same in terms of use? I am using gnu c++ compiler in codeblocks.

Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
  • 5
    This produces *undefined behavior* and you cannot rely on its results. This is essentially accessing an array out-of-bounds. If you Google you will fine other posts [like here](http://stackoverflow.com/questions/1239938/c-accesses-an-array-out-of-bounds-gives-no-error-why) – James Adkison Jan 31 '15 at 06:00
  • You are accessing memory not allocated to you. This is undefined behavior, and this type of situation is basically unique to the C++ (and C) language. – PaulMcKenzie Jan 31 '15 at 06:01
  • Its similar to doing "int *a;" and then using it. It will work some of the time until it doesn't. – waterlooalex Jan 31 '15 at 06:09

1 Answers1

6

You want five ints. Of course you should use

int *a=new int[5];

Since you are learning C++, it is wise to learn about Undefined Behavior.

You may expect C++ to stop you or warn you if you are doing something that you shouldn't be doing, such as treating an int as if it were an int[5].

C++ isn't designed to track these sorts of mistakes. If you make them, C++ only promises that it makes no promises what will happen. Even if the program worked the last time you ran it, it may not work the next time.

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
  • 1
    `> If you make them, C++ only promises that it makes no promises what will happen. Even if the program worked the last time you ran it, it may not work the next time.` c++ in a nutshell – Alex Mandelias Oct 25 '20 at 08:03