How do I create an array in C++ which is on the he

2019-04-19 14:08发布

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:

#define SIZE 262144
int myArray[SIZE];

However, it appears that when I try and add elements past a certain point, the values are different when I try to access them. I understand that this is because there is only a finite amount of memory on the stack, as opposed to the heap which has more memory.

I have tried the following without much luck (does not compile):

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

And then I considered using malloc, but I was wondering if there was a more C++ like way of doing this...

#define SIZE 262144
int *myArray = (int*)malloc(sizeof(int) * SIZE);

Should I just go with malloc?

7条回答
ゆ 、 Hurt°
2楼-- · 2019-04-19 15:08

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];
查看更多
登录 后发表回答