Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

c++ - Create a 2D array with variable sized dimensions

I want to be able to create a 2d array the size of the width and height I read from a file, but I get errors when I say:

int array[0][0]
array = new int[width][height]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should use pointer to pointers :

int** array;
array = new int*[width];
for (int i = 0;i<width;i++)
    array[i] = new int[height];

and when you finish using it or you want to resize, you should free the allocated memory like this :

for (int i = 0;i<width;i++)
    delete[] array[i];
delete[] array;

To understand and be able to read more complex types, this link may be useful :

http://www.unixwiz.net/techtips/reading-cdecl.html

Hope that's Helpful.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...