簡體   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