双指针问题
谁能告诉我这段代码有什么问题
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;
当我删除 y 时编译器总是触发一个断点 请注意,我不想删除对象“x” 谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
好吧,您刚刚分配了一个指向 int 的指针数组,该数组足够大以容纳...零个元素。在循环中,您将:
j
。x
的值分配给...y
的每个其他元素...如前所述,超出数组范围的元素。我真的不知道你想在这里完成什么。再来一点背景怎么样?您通过在 y 范围之外进行赋值来调用未定义的行为,因此此后任何事情都可能发生。
Well, you have just allocated an array of pointers to int that big enough to fit... zero elements. In your loop you are:
j
.x
to... every other element ofy
... 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.当你初始化 'y' 时,它的长度为零,因为 i 是 0。
When you initialized 'y' it has zero length since i is 0.
分配
您可能想
在“Then”中
0 个元素。在 lop 中,您可能打算迭代
j
,但每次循环迭代都会对i
进行两次增量:同样在该循环中,您将每个元素设置为指向相同的 5元素数组。我很确定你确实想要这样的东西:
That line
you probably meant to be
Then in
you allocate for 0 elements. And in the lop you probably mean to iterate over
j
, but do incrementation oni
twice per loop iteration:Also in that loop you set each element to point to the same 5 element array. I'm pretty sure you're actually want something along this:
y 是零长度,因为当你初始化它时 i==0
所以断点是在第二个循环中访问 y[1] 时。
但这为什么要增加两次 i 呢?
y is zero-length because when you initialize it i==0
so the breakpoint is when you access y[1] in the second loop.
but this why increment twice i?
试试这个:
你不应该在代码中使用常量,除非为其声明别名变量。
Try out this:
you shouldn't use constants in your code, except when declaring alias-variables for it.