How do I create an array in C++ which is on the heap instead of the stack?

后端 未结 7 1968
小蘑菇
小蘑菇 2021-02-07 05:55

I have a very large array which must be 262144 elements in length (and potentially much larger in future). I have tried allocating the array on the stack like so:



        
相关标签:
7条回答
  • 2021-02-07 05:57

    new allocates on the heap.

    #define SIZE 262144
    int * myArray = new int[SIZE];
    
    0 讨论(0)
  • 2021-02-07 06:03

    The more C++ way of doing it is to use vector. Then you don't have to worry about deleting the memory when you are done; vector will do it for you.

    #include <vector>
    
    std::vector<int> v(262144);
    
    0 讨论(0)
  • 2021-02-07 06:04

    As the number is not necessarily known at compile time, the type is a pointer:

    int *myArray = new int[262144];
    
    0 讨论(0)
  • 2021-02-07 06:08

    You'll want to use new like such:

    int *myArray = new int[SIZE];
    

    I'll also mention the other side of this, just in case....

    Since your transitioning from the stack to the heap, you'll also need to clean this memory up when you're done with it. On the stack, the memory will automatically cleanup, but on the heap, you'll need to delete it, and since its an array, you should use:

    delete [] myArray;
    
    0 讨论(0)
  • 2021-02-07 06:11

    The reason the first try didn't work is that the syntax is incorrect. Try this:

    int *myArray = new int[SIZE];
    
    0 讨论(0)
  • 2021-02-07 06:15

    I believe

    #define SIZE 262144
    int *myArray[SIZE] = new int[262144];
    

    should be

    #define SIZE 262144
    int *myArray = new int[262144];
    

    or better yet

    #define SIZE 262144
    int *myArray = new int[SIZE];
    
    0 讨论(0)
提交回复
热议问题