Where and Why Use Int A=New Int

Difference between int and new int()

int myNumber;

int myNumber = 0;

int myNumber = new int();

The effect should be exactly the same, you can try to ILDASM them if you're doubtful

What is the difference between int *a = new int and int *a = new int()?

int *a = new int;

a is pointing to default-initialized object (which is uninitialized object in this case i.e the value is indeterminate as per the Standard).

int *a = new int();

a is pointing to value-initialized object (which is zero-initialized object in this case i.e the value is zero as per the Standard).

int** a = new int*[n](); What does this function do?

As you (should) know, int *a = new int[n]; allocates an array of ints with size n.

So, in general, T *a = new T[n]; allocates an array of Ts with size n.

Now if you substitute T = int *, you'll get int **a = new int*[n];, which allocates an array of int *s (that is, of pointers to int).

Adding () on the right zeroes every pointer in the array (otherwise they would be uninitialized).

Why int[] a = new int[1] instead of just int a?

int a

defines a primitive int.

int[] a = new int[1];

defines an array that has space to hold 1 int.

They are two very different things. The primitive has no methods/properites on it, but an array has properties on it (length), and methods (specifically its on clone method, and all the methods of Object).

Arrays are a bit of a weird beast. They are defined in the JLS.

In practice, it would make sense to do this when you need to interact with an API that takes an array and operates on the results. It is perfectly valid to pass in a reference to an array with 0, 1, or n properties. There are probably other valid reasons to define an array with 1 element.

I can't think of any use cases where you would want to define an array with one element, just to bypass the array and get the element.

What is the difference between “int *a = new int” and “int *a = new int [5]?

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.



Related Topics



Leave a reply



Submit