-2

I am implementing BST and need suggestion from you. The code has 2 structures. I need to allocate link structure within item structure. how would I do that? Do I need to allocate both item->link->left & item->link->right? Please explain by example?

struct link;
struct link
{
   struct link *left;
   struct link *right;
};

struct item
{
   struct link link;
   uint8_t c;
};

In somewhere insert function

item *temp = NULL;

// How would I allocate memory ??

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
samprat
  • 2,150
  • 8
  • 39
  • 73

2 Answers2

0

First, you have to allocate memory for item.

item *temp = NULL;
temp = malloc(sizeof(item)); // alocate memory for 1 item

After you have the item you have to allocate memory for both left and right links

temp->link.left = malloc(sizeof(link));
temp->link.left = malloc(sizeof(link));

Please notice the ., it's there because link from item it's not a pointer.

adricadar
  • 9,971
  • 5
  • 33
  • 46
  • 1
    you should not cast the return value of malloc: http://stackoverflow.com/a/605858/3684343 – mch Jun 16 '15 at 20:30
0

The list struct is a member inside the stack struct. The stack encapsulates the list. This is a way to malloc and initialize your scenario using a couple functions. Hope it helps!

typedef struct currentPos{
   int x;
   int y;
   currentPos * next;
}currentPos;

typedef struct stack
{
     currentPos * list;
}stack;

int main(){
     stack * myStack;
     myStack = malloc(sizeof(stack)*1);  // mallocing shell
     myStack = createStack(myStack);
     return(0);
 }

 stack * createStack(stack * myStack)
 { 
     myStack->list = createList();
     return(mtStack);
 }

 currentPos * createList()
 {
     currentPos * theHead;
     theHead = malloc(sizeof(currentPos)*1);   // mallocing inside
     theHead->x= 0;
     theHead->y=0;
     theHead->next = NULL
     return(theHead);
}