c双指针数组
以下是我目前的代码。 我的教授告诉我们使用双指针来创建一个指针数组
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;
部分主要function
hashtbl=malloc(sizeof(struct dict)); hashtbl->tbl=malloc(sizeof(struct word)*256); int i; for(i=0;itbl[i]=NULL; }
这是实现这种双指针数组的正确方法吗?
并正在使用
hashtbl->tbl[i] = .....
访问该空间的正确方法?
hashtbl->tbl=malloc(sizeof(struct word)*256);
应该是
hashtbl->tbl=malloc(sizeof(struct word *)*256);
因为hashtbl->tbl
是一个struct word *
的数组
要初始化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); }
要解除分配:
for (int i = 0; i < 256; i++) { free(hashtbl->tbl[i]); } free(hashtbl->tbl); hashtbl->tbl = NULL;