Create a 2D array with variable sizes

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

int array[0][0] array = new int[width][height] 
+4
source share
3 answers

You should use a 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 want to resize, you must free the allocated memory as follows:

 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 this helps.

+13
source

Try as follows:

  int **array; // array is a pointer-to-pointer-to-int array = malloc(height * sizeof(int *)); if(array == NULL) { fprintf(stderr, "out of memory\n"); exit or return } for(i = 0; i < height ; i++) { array[i] = malloc(width * sizeof(int)); if(array[i] == NULL) { fprintf(stderr, "out of memory\n"); exit or return } } array = new int*[width]; if(array == NULL) { fprintf(stderr, "out of memory\n"); exit or return } else { for (int i = 0;i<width;i++) array[i] = new int[height]; } 
+1
source

If the array is rectangular, as in your example, you can do this with only one distribution:

 int* array = new int[width * height]; 

This effectively aligns the array in one dimension, and it is much faster.

Of course this is C ++, why don't you use std::vector<std::vector<int> > ?

+1
source

Source: https://habr.com/ru/post/1346156/


All Articles