繁体   English   中英

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

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

请帮助我在 C 中实现 function ,它采用数组的指针并返回该数组中的元素数。 我有一个 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));

在为 my_array 创建一个堆 memory 后,该数组添加了 n 个元素(n<=100)。 我正在尝试编写的 function 看起来像这样:

int Count(My_Type *array)

太感谢了!

在 C 中是不可能的。 C arrays 没有关于其长度或类型的任何元数据。 唯一的方法是将大小存储在数组中或使用更复杂的数据类型。

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

一些备注: malloc(sizeof(My_Type)); 不要在sizeof only 对象中使用类型。 如果您更改 object 的类型,则无需更改其他代码。 例如,要遵循类型表单,您的问题只需更改typedef

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

代码的 rest 将计算正确的尺寸而无需任何更改。 它更安全,更不容易出错。

暂无
暂无

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

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