Domanda

I'm not good at English language. But I want to be better.

I'm trying to know-more about Pointer while I have some problem.

Some lines of code:

main()
{    
     // Declerations
     int y = 99;
     int** p = new int*[2];


     // Set value
     // Ok
     for (int i=0; i<2; i++)
         p[i] = new int(y--);

     /* This case, it's fail
     for (int i=0; i<2; i++, p++)
         *p = new int(y--);
     */

     //Print
     for (int i=0; i<2; i++)
         cout << p[i][0] << " ";

     // release memory
     for (int i=0; i<2; i++)
         delete p[i];
     delete[] p; 

     getch();
}

This is my thinking about **pointer in this code block.

http://i.stack.imgur.com/EJaUX.png

I don't know why It doesn't work at "This case". Help me, I want an explanation. Thanks.

È stato utile?

Soluzione

When you modify p in the loop (p++) you loose the original pointer, so after the loop p will point somewhere else. All dereferencing of p after that loop will cause undefined behavior.

If you want that outcommented loop to work, without changing p, you have to do it using a temporary variable:

int** t = p;
for (int i=0; i<2; i++, t++)
    *t = new int(y--);

Note: If you run both allocation loops, you will have a memory leak as the pointers allocated by the first loop will be overwritten.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top