簡體   English   中英

使用指針到指針訪問結構中的指針

[英]Using a pointer-to-pointer to access a pointer-to-pointer in a structure

我有一個指向結構的指針,並且我正在嘗試訪問該結構內的指針到指針的指針。 我不斷收到錯誤消息:“在結構或聯合體中請求成員'buckets'”。 我在錯誤旁評論。 所以我的問題是,如何正確訪問存儲桶並為其分配內存。

typedef struct bucket {
  char *key;
  void *value;
  struct bucket *next;
} Bucket;

typedef struct {
  int key_count;
  int table_size;
  void (*free_value)(void *);
  Bucket **buckets;
} 


int create_table(Table ** table, int table_size, void (*free_value)(void *)){
  int iterate = 0;
  *table = malloc(sizeof(Table));

  if(table && table_size != 0) {
    (*table)->key_count = 0;
    (*table)->table_size = table_size;
    (*table)->free_value = free_value;
    (*table)->buckets = malloc(table_size * sizeof(Bucket));  /* Error is here */

    while(iterate < table_size)
      *table->buckets[iterate++] = NULL;
    return SUCC;
  }
  return FAIL;
}

根據您的分配情況:

(*table)->buckets = malloc(table_size * sizeof(Bucket));

似乎您正在嘗試為table_size存儲桶而不是為bucket的table_size指針創建空間。 該分配應為:

(*table)->buckets = malloc(table_size * sizeof(Bucket*)); 

我認為該錯誤在while循環中進一步下降。 運算符->優先於[],優先於*,因此,您實際上是在說*(table-> buckets [iterate ++]),而table是指針指針,因此沒有名為bucket的成員。

(注意:您缺少第二個typedefTable;

 int create_table(Table ** table, int table_size, void (*free_value)(void *)){ int iterate = 0; *table = malloc(sizeof(Table)); if(table && table_size != 0) { 

這是不對的。 分配內存之前,應該先測試table ,然后再測試*table

  (*table)->key_count = 0; (*table)->table_size = table_size; (*table)->free_value = free_value; (*table)->buckets = malloc(table_size * sizeof(Bucket)); /* Error is here */ 

在這里,您正在為table_size號的Bucket分配空間,但是將內存分配給了指向Bucket指針。 看起來您想分配table_size數量的指針Bucket

  while(iterate < table_size) *table->buckets[iterate++] = NULL; 

這與*(table->buckets[iterate++]) ,這顯然是錯誤的。 table不是指向struct的指針, *table是。 這是您真正的錯誤所在。


我可能會這樣寫:

typedef struct {
  int key_count;
  int table_size;
  void (*free_value)(void *);
  Bucket **buckets;
} Table;

int create_table(Table **table, int table_size, void (*free_value)(void *))
{
  if (!table || table_size == 0) {
    return FAIL;
  }
  *table = malloc(sizeof(Table));
  if (*table) {
    (*table)->key_count = 0;
    (*table)->table_size = table_size;
    (*table)->free_value = free_value;
    (*table)->buckets = malloc(table_size * sizeof(Bucket *));
    if ((*table)->buckets) {
      int iterate = 0;
      while(iterate < table_size)
        (*table)->buckets[iterate++] = NULL;
      return SUCC;
    }
  }

  if (*table) {
    free ((*table)->buckets);
  }
  free (*table);
  return FAIL;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM