[英]What is the syntax for a function signature which returns an array of struct pointers in C?
I need a function to return an array of pointers to structs. 我需要一个函数来返回指向结构的指针数组。 What is the syntax for this? 这是什么语法? Conceptually I'm thinking struct my_struct *[] create_my_struct_table(int arr[], size_t length);
从概念上讲,我在考虑struct my_struct *[] create_my_struct_table(int arr[], size_t length);
But this does not work. 但这是行不通的。 I am not trying to return an array of struct my_struct
but rather an array of struct my_struct *
. 我不是要返回struct my_struct
数组,而是要返回struct my_struct *
数组。
You cannot return an array in C. You can return a struct
that contains an array (which may be an array of pointers). 不能返回C.你的阵列可以返回一个struct
包含数组(其可以是指针数组)。 You can also return a pointer to an array, which must have a lifetime longer than the function that returns it, such as a static array or one returned from calloc()
. 您还可以返回一个指向数组的指针,该数组的寿命必须比返回它的函数长,例如静态数组或从calloc()
返回的函数。 If it is dynamically-allocated, the caller must free it once and only once. 如果它是动态分配的,则调用者必须释放一次并且只能释放一次。 Or the caller can allocate the destination array and pass its address as an output parameter. 或者,调用者可以分配目标数组,并将其地址作为输出参数传递。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.