0

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?

5
  • What do you want your array of pointers to point to? Commented Nov 14, 2011 at 2:52
  • it should point to struct word Commented Nov 14, 2011 at 2:55
  • So initialize struct word **tbl? Commented Nov 14, 2011 at 2:57
  • 1
    I mourn the loss of our whitespace :( Commented Nov 14, 2011 at 2:58
  • @Nayefc I did that hashtbl->tbl=malloc(sizeof(struct word *)*256); Commented Nov 14, 2011 at 3:00

2 Answers 2

3

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 *

Sign up to request clarification or add additional context in comments.

Comments

0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.