简体   繁体   English

返回包含指向C中数组的指针的结构的函数

[英]Function that return a structure that contains a pointer to array in C

First few parts of code: 前几部分代码:

    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;
    }

then in main(): 然后在main()中:

wynik get = calc(&tab, tab_size);

Using debugger I discovered that in calc() out.t points to an array, but in main() get.t points to some weird things. 使用调试器我发现在calc()out.t指向一个数组,但在main()中get.t指向一些奇怪的东西。 How to fix it? 怎么解决?

out.t contains the address of the local variable sorted . out.t包含已sorted的局部变量的地址。 When the function returns, this address is no longer valid because the local variable went out of scope. 函数返回时,此地址不再有效,因为局部变量超出范围。

I see no reason here that out.t should be int** instead of int* . 我认为没有理由说out.t应该是int**而不是int* If you change it to be int* and just set its value with out.t = sorted , it should work correctly. 如果将其更改为int*并仅使用out.t = sorted设置其值,则它应该可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM