在C中返回结构指针数组的函数签名的语法是什么?

时间:2019-06-02 04:18:11

标签: c arrays

我需要一个函数来返回指向结构的指针数组。这是什么语法?从概念上讲,我在考虑struct my_struct *[] create_my_struct_table(int arr[], size_t length);,但这行不通。我不是要返回struct my_struct的数组,而是要返回struct my_struct *的数组。

2 个答案:

答案 0 :(得分:0)

struct mystruct ** foo(struct mystruct **arrayOFpointers)
{

    int i =0;
    while(arrayOFpointers[i] != NULL)
    {
        //do something with *arrayOFpointers[i]
        i++;
    }
    return arrayOFpointers;
}
int main()
{
    int n = 10; // size
    struct mystruct *pointers[n];
    pointers[0] = (struct mystruct*)malloc(sizeof(struct mystruct));
    //allocate all other pointers in the array like this

    struct mystruct *processed_Pointers[n];

    processed_Pointers = foo(pointers);
return 0;
}

答案 1 :(得分:0)

您不能在C中返回数组。您可以返回包含数组(可能是指针数组)的struct。您还可以返回一个指向数组的指针,该数组的生存期必须比返回它的函数长,例如静态数组或从calloc()返回的数组。如果它是动态分配的,则调用者必须释放一次并且只能释放一次。或者,调用方可以分配目标数组,并将其地址作为输出参数传递。