【问题标题】:Deleting a pointer returned from a function?删除从函数返回的指针?
【发布时间】:2017-03-25 03:52:47
【问题描述】:

我正在为学校编写一个编码作业,要求我们使用数组而不是向量(重点是学习指针和内存管理)。我遇到的问题是我无法删除从函数返回的指针——下面是我所说的一个例子。

int* rndFunc(){
    int *rndValue = new *int[5];

    return rndValue;
}
int main(void){
    int *foo;
    foo = rndFunc();

    delete[] foo; //this is the issue, I get an invalid pointer error.

}

【问题讨论】:

  • 函数中的bar 是什么?
  • 我搞砸了我的代码示例 -- bar 应该是 rndValue。
  • @HighMans 学习复制/粘贴,然后您就不会弄乱您的示例。现在我们怎么能相信你没有搞砸其他事情呢?如果你把其他事情搞砸了,你可能得不到正确的答案,你只会浪费你和其他人的时间。因此,请使用复制/粘贴并确保您所询问的代码正是您正在努力解决的问题。
  • 回到我之前的评论,我没有收到您指出的错误。

标签: c++ pointers memory-management


【解决方案1】:

有两个错误:

int* rndFunc(){
    int *rndValue = new int[5]; // instead of int *rndValue = new *int[5];

    return rndValue; // Instead of return bar;
}

【讨论】:

  • 在你的第一个修复之后给了我这个:错误:'*' token int *rndValue = new *int[5];
  • 这应该可以。我的修复编译得很好。您确定在该行中删除了 int[5] 之前的第二个“*”吗??
  • 你的错误仍然是:int *rndValue = new *int[5].
  • int *rndValue = new *int[5] ----> int *rndValue = new int[5]
  • 哦,好吧!我现在明白了。谢谢。
猜你喜欢
  • 2011-12-06
  • 1970-01-01
  • 2010-12-25
  • 2011-03-09
  • 2013-02-20
  • 2019-08-22
  • 2011-07-19
  • 1970-01-01
  • 2013-04-10
相关资源
最近更新 更多