0

I just finished reading this excellent post on hashtables What is a hash table and how do you make it in C? My question is this: Why is it that we are constantly mallocing node pointers instead of actual nodes based on our struct? Is creating a struct node pointer just as good as creating the struct itself? I thought, with respect to the linked lists in our hashtable, we needed both a pointer to our struct nodes, in addition to the nodes themselves. I know I'm missing something, but I'm not sure what. Any insight or direction would be greatly appreciated!

Community
  • 1
  • 1
Ryan
  • 1,312
  • 3
  • 20
  • 40
  • 3
    `node* newptr = malloc(sizeof(node));` allocates memory for a `node` and puts the *address* of that node in `newptr`. So it's not allocating a pointer, it *is* allocating an actual node. – user3386109 Nov 02 '16 at 00:17
  • @user3386109 Ok. So, the existence of the address returned by malloc implies the existence of the struct node. Many thanks! – Ryan Nov 02 '16 at 00:24
  • 1
    always check the return of `malloc`.. if it gives you NULL it was unable to allocate enough space for your request, and you'll have to gracefully handle that error – yano Nov 02 '16 at 00:26
  • 2
    `node* newptr = malloc(sizeof(node));` you are right we a allocating a node pointer, but the pointer points to a space of `sizeof(node)` in memory its essentially a node that the pointer points to. – tesseract Nov 02 '16 at 00:40

0 Answers0