简体   繁体   中英

c double pointer array

The following is my current code. My professor told us to use a double pointer to create an array of pointers

 struct dict {
  struct word **tbl;
  int (*hash_fcn)(struct word*);
  void (*add_fcn)(struct word*);
  void (*remove_fcn)(struct word*);
  void (*toString_fcn)(struct word*);
};

struct word {
  char *s;
  struct word *next;
};

struct dict *hashtbl;

Part of the main function

  hashtbl=malloc(sizeof(struct dict));
  hashtbl->tbl=malloc(sizeof(struct word)*256);
  int i;
  for(i=0;i<256;i++)
  { 
    hashtbl->tbl[i]=NULL;
  }

is this the correct way to implement this sort of double pointer array?

and is using

hashtbl->tbl[i] = ..... 

the right way of accessing that space?

hashtbl->tbl=malloc(sizeof(struct word)*256);

should actually be

hashtbl->tbl=malloc(sizeof(struct word *)*256);

since hashtbl->tbl is an array of struct word *

To initialize struct word **tbl :

hashtbl->tbl = malloc(sizeof(struct word *)*256);

if (hashtbl->tbl == NULL) {
    printf("Error malloc");
    exit(1);
}

for (int i = 0; i < 256; i++) {
    hashtbl->tbl[i] = malloc(sizeof(struct word));
    if (hashtbl->tbl[i] == NULL) {
        printf("Error malloc");
        exit(1);
}

To deallocate:

for (int i = 0; i < 256; i++) {
    free(hashtbl->tbl[i]);
}
free(hashtbl->tbl);
hashtbl->tbl = NULL;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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