how is it working?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sanketbarot
    New Member
    • Sep 2006
    • 30

    how is it working?

    Hello friends

    suppose i want to defined a 2 dimensional array using pointer. for that i follow the following procedure(given in book). it is working perfactly but i am not getting it.

    suppose row =2 and coloum =3
    int **p;


    p = new int*[2]; //Line 1

    *p = new int[3]; /// line2
    ++*p = new int[3]; //line 3
    ++*p = new int[3; // Line 4



    Now what exactly it is doing?
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    p = new int*[2]; // 1 Allocates an array of integer pointers

    *p = new int[3]; /// Allocates an array of integers and assigns it to the first entry in p

    ++*p = new int[3]; // Increment p to point to the second array entry allocated in 1, allocate an array of integers and assign it to this new location

    ++*p = new int[3]; // Increment p to point to the third array entry allocated in 1, however 1 only allocated 2 array entries so we are now pointing at unallocated data. Allocate an array of integers and assign it to this new location. Additionally since we haven't saved p we no longer and a reference to the originally allocated data so a memory leak may happen

    It is equivilent to this

    p = new int*[2];
    p[0] = new int[3];
    p[1] = new int[3];
    p[2] = new int[3];

    Just using pointer arithmatic rather than array notation.

    Comment

    Working...