如何获得的结构在C中动态创建数组的长度? [英] How to get the length of a dynamically created array of structs in C?
问题描述
目前我正在试图获得一个动态生成的数组的长度。它是结构的数组:
I am currently trying to get the length of a dynamically generated array. It is an array of structs:
typedef struct _my_data_
{
unsigned int id;
double latitude;
double longitude;
unsigned int content_len;
char* name_dyn;
char* descr_dyn;
} mydata;
我intialize我的数组这样的:
I intialize my array like that:
mydata* arr = (mydata*) malloc(sizeof(mydata));
和再调整它使用的的realloc 并开始与数据来填充它。
And then resized it using realloc and started to fill it with data.
我然后试图用code描述<一个得到它的大小href=\"http://stackoverflow.com/questions/37538/how-do-i-determine-the-size-of-my-array-in-c\">here.
I then attempted to get its size using the code described here.
sizeof(arr) / sizeof(arr[0])
此操作返回 0 ,即使我的数组包含两个元素。
This operation returns 0 even though my array contains two elements.
可能有人请告诉我,我在做什么错了?
Could someone please tell me what I'm doing wrong?
推荐答案
如果你需要知道一个动态分配的数组的大小,你要跟踪它自己。
If you need to know the size of a dynamically-allocated array, you have to keep track of it yourself.
的的sizeof(ARR)/ sizeof的(ARR [0])
技术只适用于数组的大小在编译时是已知的,对C99的的variable-length阵列的。
The sizeof(arr) / sizeof(arr[0])
technique only works for arrays whose size is known at compile time, and for C99's variable-length arrays.
这篇关于如何获得的结构在C中动态创建数组的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!