简体   繁体   中英

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

通过使用int someInts[3]声明新的整数数组与使用int* someInts = new int[3]声明之间有什么区别?

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.

The difference that's generally important (especially when you're dealing with something other than int s) 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).

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM