Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with double pointers

can anyone tell me what is wrong with this piece of code

int* x=new int(5) ;
int i =0;
int** y = new int*[i];
for(int j = 0 ;j<5 ; j++)
{
     y[i++]=x;
}
delete[] y;

the compiler always triggers a breakpoint when I delete y note that I don't want to delete the object "x" thanks

like image 933
neoProgram Avatar asked Dec 09 '25 09:12

neoProgram


1 Answers

int i =0;
int** y = new int*[i];

Well, you have just allocated an array of pointers to int that big enough to fit... zero elements. In your loop you are:

  1. Writing outside the bounds of your array (remember, zero elements...)
  2. Incrementing your loop counter twice for each iteration.
  3. Never using your loop variable j.
  4. Assigning the value of x to... every other element of y... that is outside the bounds of the array as previously mentioned.

I don't really know what you are trying to accomplish here. How about a bit more background? You are invoking undefined behavior by assigning outside the bounds of y, so anything can happen after that.

like image 119
Ed S. Avatar answered Dec 11 '25 23:12

Ed S.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!