9

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]
3

3 Answers 3

22

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.

2
  • 2
    ...and remember to delete with delete[].
    – sje397
    Apr 1, 2011 at 1:43
  • TAMER I think you need to swap your heights and widths around.
    – jonsca
    Apr 1, 2011 at 1:44
1

If the array is rectangular, as in your example, you can do it with just one allocation:

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

This effectively flattens the array into a single dimension, and it's much faster.

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

1

Try this way:

  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];
    }
2
  • 1
    You should avoid malloc in C++.
    – sje397
    Apr 1, 2011 at 1:44
  • 1
    This is a really C-ish way to do things. Plus, the fprintf calls really have no place here. It could use some cleanup.
    – Jon
    Apr 1, 2011 at 1:45

Not the answer you're looking for? Browse other questions tagged or ask your own question.