1

谁能帮我这个?假设我有以下结构:

typedef struct mystruct{
    int data1;
    int data2;
}mystruct;

我使用以下代码创建了一个结构数组:

main(void) {
    mystruct **new_mystruct = function();
    ... need to know the length of new_mystruct here ...
}

mystruct **function(){
    ... code to determine length of array here ...
    mystruct **new_mystruct= malloc(length_of_array * sizeof(mystruct));
    ... code to fill array here ...
    return new_mystruct;
}

假设 length_of_array 在函数运行时动态生成,那么返回数组长度的最佳方法是什么?

我希望我说得通。先感谢您。

4

4 回答 4

2

您可以将长度作为对函数的引用传递,并让函数将其填充:

mystruct *function(size_t *size)
{
    /* ... */

    mystruct *new_mystruct = malloc(length_of_array * sizeof(mystruct))
    *size = length_of_array;

    /* ... */

    return new_mystruct;
}

int main(void)
{
    /* ... */

    size_t size;
    mystruct *new_mystruct = function(&size);

    /* ... */
}
于 2013-05-25T11:29:44.163 回答
2

制作包装结构:

typedef struct_array_
{
    mystruct * p;
    size_t size;
} struct_array;

您的创建函数可以按值返回:

struct_array create_array(size_t n)
{
    mystruct * p = malloc(n * sizeof *p);
    struct_array result = { p, n };
    return result;
}

你应该做一个匹配的清理功能:

void destroy_array(struct_array a)
{
    free(a.p);
}

您还可以创建一个用于创建副本的copy_array函数。memcpy

于 2013-05-25T11:32:23.553 回答
0
size_t function(MyStruct *mystruct)
{
    /*...*/
    mystruct = malloc(length_of_array * sizeof(MyStruct)); 
    /*...*/
    return length_of_array;   
}

并使用

MyArray *new_array;
size_t lenght;

lenght = function(new_array);
于 2013-05-25T11:31:01.727 回答
0

您可以返回包含长度和指向已分配数组的指针的结构(或指向结构的指针),也可以传入指向变量的指针以接收长度。

int length;

mystruct **new_mystruct = function(&length);

我更喜欢 stuct 方法。

于 2013-05-25T11:31:11.100 回答