c - 存储动态结构数组的长度

标签 c

谁能帮我解决这个问题?假设我有以下结构:

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 是在函数运行时动态生成的,返回数组长度的最佳方法是什么?

希望我说的有道理。提前谢谢你。

最佳答案

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

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

    /* ... */
}

关于c - 存储动态结构数组的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16749035/

相关文章:

C fork 不起作用

c - 使用调试器查找整数值

c - 这段代码有什么问题,我不能将指针和无符号值加在一起吗?

c - 这个双重声明在 C 中是什么意思?

c++ - 寻找一种有效的数据结构来进行快速搜索

c - 是不是对于外部变量和静态变量,初始化器必须是常量表达式?

c - C 中优先级 and++ 和 * 一元运算符的问题

c - 了解 double 和整数

c - 程序不会等待用户输入 scanf ("%c",&yn);

android - SIGSEGV memcpy 和 memmove