![](/img/trans.png)
[英]Declaring an array of pointers to structures in C, but not allocating memory for structure until needed
[英]Memory allocating array of structure pointers in c
我想傳遞一個結構地址的指針數組,該指針的大小和訪問結構成員的大小都不同。 但是通過傳遞結構對象的數組,數據是不規則的,並且庫函數發出了SIGABRT信號。 這是我的代碼的一部分-
struct data *device_info;
device_info = malloc(device_count*sizeof(void );
ipbt_database_manager_get_device_info(device_info, "all", device_count);
這是功能定義-
bool ipbt_database_manager_get_device_info(struct data *dev_info_ptr, char *device_id, int device_count)
{
struct node *current_device_info = first_device_info;
int count = 0;
if (!strcmp(device_id,"all")) {
while (current_device_info != NULL) {
dev_info_ptr[count] = current_device_info->node_data;
count++;
current_device_info = current_device_info->next;
}
}
您的函數需要一個指向結構的指針(可能是連續內存中的許多謊言之一)。
這應該分配足夠的內存,這是單個struct data
乘以device_count
的內存:
struct data *device_info = malloc(sizeof(*device_info) * device_count);
ipbt_database_manager_get_device_info(device_info, "all", device_count);
我省略了對NULL的檢查(必須執行),並將指針定義與其初始化結合在一起。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.