0

I'm having trouble understanding pointers with nodes and arrays. assume we have this structure:

typedef struct node
{
    int x;
    struct node *next;
}node;

if I have an array of node pointers like:

node *table[50];

can I say:

table[0] = malloc(26 * sizeof(node*));

is it possible? I mean table[0] is a pointer to a node but malloc will return a pointer to a pointer of a node. In fact, I want to make more than one (for each pointer in the new array I want to create a new array of node pointers and at last each element of the last array will have a linked list) Hope I was clear and excuse me for my bad English.

Ali
  • 30
  • 6
  • Possible, but not a good idea. `table[0]` is `node*`, so it points `node` and the size calculation `26 * sizeof(node*)` don't match this. – MikeCAT Nov 06 '20 at 23:16
  • You want to create arrays of node pointers, so why don't you make each elements point at (arrays of) node pointers (`node **table[50];`)? – MikeCAT Nov 06 '20 at 23:18
  • The general rule is that if you're giving a type argument to `sizeof()` in `malloc()`, it should have 1 less `*` than the type you're assigning to. – Barmar Nov 06 '20 at 23:18
  • 1
    `node` is part of a linked list. You don't need to make an array of them -- each element of `table` points to just a single node, which is the first node in the list. – Barmar Nov 06 '20 at 23:19
  • 1
    This looks like a hash table. Each element of `table` is a hash bucket. The bucket itself is a linked list. So `table[i]` points to a single node, which is the first node in the list. The list grows dynamically using the `next` pointers. – Barmar Nov 06 '20 at 23:22
  • @Barmar it is a hash table but I want to make another idea. @MikeCAT thanks for replying, the example code is ( ```node *table[50];``` ) so I was thinking if there is a way to make what I want without changing it. – Ali Nov 06 '20 at 23:38
  • `table[0] = malloc(26 * sizeof(node))`. That makes `node[0]` point to an array of 26 nodes. – Barmar Nov 06 '20 at 23:45

1 Answers1

0

malloc is allocate space for your data.

table = (node*)malloc(50 * sizeof(node));

now table is a pointer to a space in memory that can store 50 node.

then you can use this as an array:

table[n]

ido25
  • 1
  • 1
  • 2
  • I didn't quite get that. I want to know if the idea is right without changing the original ```node *table[50];``` @ido25 – Ali Nov 06 '20 at 23:40
  • you cant. `[]` is an array, holding the actual contents. `*` is a pointer and it dynamically allocate. https://stackoverflow.com/questions/11555997/c-c-int-vs-int-pointers-vs-array-notation-what-is-the-difference – ido25 Nov 07 '20 at 00:40