【问题标题】:Allocating array in quadriple pointer [closed]在四元指针中分配数组[关闭]
【发布时间】:2015-09-30 22:48:26
【问题描述】:

假设我有 int ****ptr;。我想在这个 ptr 的末尾分配一个动态的一维数组,所以当我输入 ***ptr[4] 时,我会产生一个元素。请帮忙。

附言 我没有在我的实际应用程序中使用此代码,这只是理解指针如何工作的智力练习。 我不能直接做***ptr = malloc(sizeof(int)*size_of_arr)); 对吗?因为这样我将无法产生任何元素

【问题讨论】:

  • 这只是智力活动吗?如果你真的使用这样的代码,你几乎肯定走错了路。
  • 括号来拯救你..你有没有试过给你的代码加上括号?也许将过程分解为 2-3 行代码,也许使用一些本地辅助变量?
  • 没有生产级代码会使用这种结构。即使从学术角度提出这样的问题,毕竟问得也很糟糕。
  • 好吧,如果你不能回答我的问题,那不是因为它问得不好,而是因为你不知道,因为缺乏知识。
  • 你在 “假设我有 int ****ptr; 我的意思是认真的伙伴 wtf

标签: c++


【解决方案1】:
int ****ptr;
ptr = new int***();
*ptr = new int**();
**ptr = new int*();
***ptr = new int[size_of_arr];

//access (***ptr)[index]

delete[] ***ptr;
delete **ptr;
delete *ptr;
delete ptr;

【讨论】:

【解决方案2】:

请注意,***ptr[4](***ptr)[4] 不是相同的东西。索引运算符 ([4]) 优先于取消引用运算符 (*)。

int ****ptr;
ptr = new int***[5];
ptr[4] = new int**;
*ptr[4] = new int*;
**ptr[4] = new int;
***ptr[4] = 77;

delete **ptr[4];
delete *ptr[4];
delete ptr[4];
delete [] ptr;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-28
    • 1970-01-01
    • 1970-01-01
    • 2012-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多