user1215882
user1215882

Reputation: 5

Difference between int someInts[3] and int* someInts = new int[3]?

What is the difference between declaring a new integer array by using int someInts[3], versus using int* someInts = new int[3]?

Upvotes: 0

Views: 1611

Answers (4)

daniel gratzer
daniel gratzer

Reputation: 53881

When you do someInts[3], you allocate memory on the stack, this means that it will delete itself (good) but if you want to access after the function has ended you'll run into trouble as it will already have been deleted. IE:

int* returnPointerThingy(){
    int someInts[3];
    someInts[0] = 3;
    someInts[1] = 2;
    someInts[2] = 1;
    return someInts
}

This will return a null pointer since someInts has been deleted. If you try to access something in someInts god help you.

If this is similar to what you which to do you want to use the new keyword. It will allow you to allocate something on the "Heap" and it will live after the function it was declared in has ended. Thus this:

int* returnPointerThingy(){
    int* someInts = new int[3];
    someInts[0] = 3;
    someInts[1] = 2;
    someInts[2] = 1;
    return someInts
}

Will not return a null pointer and you will be able to use the values stored by someInts. However this comes with a drawback, you must delete someInts like this:

delete [] someInts

So you don't end up with memory leaks, when the heap gets taken up by pointers and such.

It depends on your situation for which to use as both are better in their own situations.

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490108

The difference that's generally important (especially when you're dealing with something other than ints) is that with when you use the latter (int *someints = new int[3];) you have to explicitly delete the data when you're done using it.

Most of the time, you want to use std::vector<int> someints(3); instead. This will (normally) allocate the space for the data similarly, but it'll automatically delete that space when the variable goes out of scope (including, for example, leaving the scope via an exception being thrown, which is much more difficult to handle correctly when you allocate/free the memory manually).

Upvotes: 3

MByD
MByD

Reputation: 137312

There are 2 main differences:

  1. The first will allocate a memory on the stack, that will be unavailable once the function returns.
    The second will allocate a memory on the freestore, which will be available until deleted.

  2. The first someInts is an array of ints, you cannot assign new address to it.
    The second is a pointer to int, so you may assign a new address to it.

Upvotes: 6

Eric Andres
Eric Andres

Reputation: 3417

Declaring int* someInts = new int[3] allocates the memory on the heap. Declaring int someInts[3] allocates it on the stack.

Upvotes: 0

Related Questions