Wednesday, November 20, 2013

use pointer to make arrays in a simple way

   // Define three address types.
   // We need to think "address type" as a type like any other
   // ordinary type such as "integer type ( int )"
   // So in our example, ADDR is just an ordinary type as int.
   // Also let's say "new" operator is to create an address. 
    typedef int* ADDR;        // Its value is address, where int stays
    typedef int** ADDR2;    // Its value is address, where ADDR stays
    typedef int*** ADDR3;   // Its value is address, where ADDR2 stays


// Goal is to create 3D array: 3 x 4 x 5= 60
// Option 2: allocate all the space at once
//    ADDR head = new int[60];

    // 1. Assign i3d, whose type is address type ADDR3,
    //    with an address containing ADDR2. 
    ADDR3 i3d = new ADDR2[3]; 
    for (int i=0; i< 3 ; ++i)
    {
        // 2. Assign i3d[i], whose type is address type ADDR2,
        //     with an address containing ADDR 
        i3d[i] = new ADDR[4];
        for (int j=0; j< 4 ; ++j)
        {
           // 3. Assign i3d[i][j], whose type is address type ADDR,
           //     with an address containing int
            i3d[i][j] = new int[5];

         // Option 2: 
         //   i3d[i][j] = head + i * 4 * 5 + j * 5;
        }
    }


// Use i3d like this:  i3d[i][j][k]

    for (int i=0; i< 3 ; ++i)
        for (int j=0; j< 4 ; ++j)
            for (int k=0; k < 5 ; ++k)
                i3d[i][j][k] = i*100 + j*10 + k;


// Release space like this in a reversed order.

    for (int i=0; i< 3 ; ++i)
    {
        for (int j=0; j< 4 ; ++j)
        {
            delete [] i3d[i][j];
        }
        delete [] i3d[i];
    }
    delete i3d;

    // Option 2: 
    // for (int i=0; i< 3 ; ++i)
    // {
    //     delete [] i3d[i];
    // }
    // delete
[] i3d;

    // delete
[] head; 




No comments:

Post a Comment