-2

Good morning, I try to build a 'game' version of Towers of Hanoi that later can either be solved manually or by the algorithm itself. The user can choose the amount of disks on the pole. Now I try to design the disks on the pole as linked list since I wanted to use those to learn understand them. The following code is of course only temporary, partly and incomplete but I would be delighted if you could help me find the bug/ tell me if I miss on something. This only handels the creation of all disks at the begin for now.

typedef struct disk{ int placeholder; struct disk *left; struct disk *right; } disk;

void pileUp(disk *pole)
{
    int disks = 0;

    disk *next = pole->right;
    pole->left = NULL;

    // input
    printf("D: ");
    scanf("%d", &disks);
    //end

    while(disks > 0)
    {
        next = malloc(sizeof(*pole)); //alloc another diskspace

        next->placeholder = disks; //placeholder value

        printf("%d\t%p\n", next->placeholder, &next); //check on each

        next = next->right; //iterate

        --disks;
    }
}

int main(int argc, char *argv[])
{
    disk pole1, pole2, pole3;

    pileUp(&pole1);

    return 0;
}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
GirlGeek
  • 1
  • 1
  • `next = next->right;` in your loop when `next` fields aren't all initialized. – Jean-François Fabre Feb 24 '18 at 11:42
  • Two things: `&next` is a pointer to the *variable* `next`, not where `next` is actually pointing (that would be plain `next`). Secondly, that's not really how linked lists work, you never have or create a linked list. `pole->right` and `next->right` will never point to anything valid, and at the start of each iteration you make `next` point somewhere completely different. – Some programmer dude Feb 24 '18 at 11:43
  • in fact you never initialize any `right`. This cannot work – Jean-François Fabre Feb 24 '18 at 11:43

1 Answers1

0

First problem in the main function: you have to instantiate the variable pole1, pole2 and pole3 as pointer to a disk type disk* pole1, pole2, pole3; then you have to allocate space for the 3 disk variables with the malloc, so now you can passed the pointer pole1 to the pileUp function.