谁能帮我解决这个问题?假设我有以下结构:
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/