Alex Rivera | Logout

Create a 2D array with variable sized dimensions

Asked 2011-04-01T01:38:41.897
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]
Edit
Report

1 Answer

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];
    }
answered 2011-04-01T01:41:26.453

Your Answer