What Does "New Int(100)" Do?

Possible Duplicate:
is this a variable or function

I mistakenly used something like:

int *arr = new int(100);

and it passes compile, but I knew this is wrong. It should be

int *arr = new int[100];

What does the compiler think it is when I wrote the wrong one?

0

4 Answers

The first line allocates a single int and initializes it to 100. Think of the int(100) as a constructor call.

Since this is a scalar allocation, trying to access arr[1] or to free the memory using delete[] would lead to undefined behaviour.

5

Wikipedia new(C++) quote:

int *p_scalar = new int(5); //allocates an integer, set to 5. (same syntax as constructors)
int *p_array = new int[5];  //allocates an array of 5 adjacent integers. (undefined values)

UPDATE

In the current Wikipedia article new and delete (C++) the example is removed.

Additionally here's the less intuitive but fully reliable C++ reference for new and new[].

4

It allocates one object of type int and initialized it to value 100.

A lot of people doesn't know that you can pass an initializer to new, there's a particular idiom that should be made more widely known so as to avoid using memset:

new int[100]();

This will allocate an array of int and zero-initialize its elements.

Also, you shouldn't be using an array version of new. Ever. There's std::vector for that purpose.

7

The first one creates a single new integer, initializes it to the value 100 and returns a pointer to it.

In C/C++ there is no difference between a pointer to an array and a pointer to a single value (a pointer to an array is in fact just a pointer to its first element). So this is a valid way to create an array with one element.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest