Thread: dynamic allocation of multidimensional arrays in c++

  1. #1

    Lightbulb dynamic allocation of multidimensional arrays in c++

    from Gulliver;

    hi there.
    i have engineered/fiddled the following code that gives no errors;

    double **matrix; //declares matrix (double pointer)

    //allocate the array somewhere else in code
    int size = ~decided at runtime;
    matrix = new double * [size]; //allocates an array of pointers to matrix that point to type double

    for (int i=0;i<size;i++){
    matrix[i] = new double [size];} //allocates an array of size to each pointer in first array

    //use array(s)
    matrix[2][3] = 12.984;

    //destroy the matrix
    for (i=0;i<size;i++){
    delete [] matrix[i];} //deletes each array within matrix

    delete [] matrix; //deletes the array of pointers


    i did this because new() doesn't let me dynamically allocate multidimensional arrays.
    The code seems to work, but i'm worried that i have abused new() and delete().

    Have i freed all of the memory i allocated?
    When using matrix[2][3], am i writing to memory i have allocated?

    i receive no errors at runtime or from the compiler....

    but i'm very new to c++, so if anyone can comment the above code i would be very grateful.
    If it is good code, then it should go in someone's book, as others could find it useful....
    ....but if it isn't i'd really like to know!


  2. #2
    S­énior Member
    Join Date
    Jan 2002
    It looks ok, depending on what you're doing it may not be very efficient (if this is a problem you may be better off allocating the memory in one chunk and calculating the offsets from the indices).

  3. #3


    Yes the program is absolutely correct. Now when a pointer is deleted the array of pointers in deleted actually,
    The term char **m,
    delete [] m;
    will cause the m pointers[array ]to be deleted which inturn will delete m[x][]; this is an automatic process..................

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. dynamic allocation from 1 instead of zero
    By cfdprogrammer in forum C Programming
    Replies: 27
    Last Post: 04-28-2009, 08:21 AM
  2. Replies: 7
    Last Post: 06-04-2008, 10:39 PM
  3. Dynamic allocation of 2 dim. arrays in classes
    By circuitbreaker in forum C++ Programming
    Replies: 4
    Last Post: 02-10-2008, 12:13 PM
  4. Replies: 16
    Last Post: 01-01-2008, 04:07 PM
  5. dynamic multidimensional arrays as function arguments
    By magda_k in forum C++ Programming
    Replies: 1
    Last Post: 03-20-2006, 04:00 PM