简体   繁体   English

使用指向 C 中的数组的指针查找数组中的元素数

[英]Find number of element in the array using the pointer to the array in C

please help me to implement function in C that take the pointer of array and return the number of elements in that array.请帮助我在 C 中实现 function ,它采用数组的指针并返回该数组中的元素数。 I have an array of type My_Type like this:我有一个 My_Type 类型的数组,如下所示:

typedef struct My_Type My_Type ;

struct My_Type {
    char *array[100];  //100 is the maximum length the array could have
}

My_Type *my_array = malloc(sizeof(My_Type));

After creating a heap memory for my_array, the array was added n number of element (n<=100).在为 my_array 创建一个堆 memory 后,该数组添加了 n 个元素(n<=100)。 The function I'm trying to write look like this:我正在尝试编写的 function 看起来像这样:

int Count(My_Type *array)

Thank you so much!太感谢了!

It is not possible in C.在 C 中是不可能的。 C arrays do not have any metadata about their length or type. C arrays 没有关于其长度或类型的任何元数据。 The only way is to store the size in the array or use more complex data type.唯一的方法是将大小存储在数组中或使用更复杂的数据类型。

typedef struct
{
    size_t size;
    int arr[];
}int_arr_t;


int_arr_t *allocate(int_arr_t *array, size_t newsize)
{
    int_arr_t *arr = realloc(array, sizeof(*arr) + newsize * sizeof(arr -> arr[0]));

    if(arr)
    {
        arr -> size = newsize;
    }
    return arr;
}

size_t getCount(int_arr_t *arr)
{
    return arr ? arr -> size : 0;
}

Some remarks: malloc(sizeof(My_Type));一些备注: malloc(sizeof(My_Type)); do not use types in the sizeof only objects.不要在sizeof only 对象中使用类型。 If you change the type of the object you will not have to change other code.如果您更改 object 的类型,则无需更改其他代码。 For example to follow type form your question only typedef has to be changed:例如,要遵循类型表单,您的问题只需更改typedef

typedef struct
{
    size_t size;
    char *arr[];
}int_arr_t;

The rest of the code will calculate the correct sizes without any changes.代码的 rest 将计算正确的尺寸而无需任何更改。 It is much safer and less prone to errors.它更安全,更不容易出错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM