【问题标题】:Function that return a structure that contains a pointer to array in C返回包含指向 C 中数组的指针的结构的函数
【发布时间】:2015-03-10 14:18:07
【问题描述】:

前几部分代码:

    typedef struct
    {
        double sr, med;
        int **t;
    }wynik;

    wynik calc(int *t[], int size)
    {
        int i, *niep = NULL, j = 0, k = 1, sum = 0;
        int *sorted = (int*)malloc(size*sizeof(int));
        wynik out;
        //coping, sorting
        for (i = 0; i < size; i++)
            sorted[i] = (*t)[i];
        qsort(sorted, size, sizeof (**t), cmp);
        out.t = &sorted;
...
    return out;
    }

然后在 main() 中:

wynik get = calc(&tab, tab_size);

使用调试器我发现在 calc() 中 out.t 指向一个数组,但在 main() 中 get.t 指向一些奇怪的东西。 如何解决?

【问题讨论】:

  • 您的结构不包含数组。它包含一个指针。
  • 很抱歉,这段代码没有任何意义。看起来您不确定指针和数组是如何工作的,因此将您的程序混淆到您不再知道它做什么的地步。最重要的是,您有内存泄漏。此代码无法挽救。

标签: c arrays structure


【解决方案1】:

out.t 包含局部变量sorted 的地址。当函数返回时,此地址不再有效,因为局部变量超出范围。

我认为这里没有理由 out.t 应该是 int** 而不是 int*。如果您将其更改为int* 并使用out.t = sorted 设置其值,它应该可以正常工作。

【讨论】:

  • 因为他在函数内部的堆上分配了内存,所以该地址在被释放之前应该保持有效,不是吗?
  • @MattKo 存储在sorted 中的地址(由malloc 分配)在释放之前一直有效。但是sorted本身的地址(&amp;sorted)在返回时就失效了。
  • 你说得对,我有点分心了,这段代码不是那么容易分析的。当然sorted的地址在栈上,但它的内容在堆上。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-30
  • 1970-01-01
  • 1970-01-01
  • 2019-07-06
  • 1970-01-01
  • 2016-04-21
相关资源
最近更新 更多