Hello. I've been trying to solve this problem but I can't and my head hurts already. Please help me.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
#define max 12
#define num 30
#define nam 24
typedef struct
{
char name[nam];
int score;
int rank;
}CONTESTANT;
typedef struct
{
CONTESTANT CA;
int next;
}HeapSpace;
typedef struct
{
HeapSpace *H;
int first;
}VirtualHeap, *VHeap;
typedef struct
{
int storage[max];
int ladder[max];
int nextrung;
}DualDataStruc, *DDS;
void initialize(DDS *D, VHeap *VH);
int myMalloc(VHeap *VH);
void myFree(VHeap *VH, int x);
int hash(char n[]);
void insert(DDS *D, VHeap *VH, int NOP);
void display(DDS D, VHeap VH);
void initialize(DDS *D, VHeap *VH)
{
int ctr;
*D = (DDS) malloc(sizeof(DualDataStruc));
*VH = (VHeap) malloc(sizeof(VirtualHeap));
(*VH)->H = (HeapSpace *) malloc(sizeof(HeapSpace) * num);
(*VH)->first = 0;
for(ctr = 0; ctr < num - 1; ctr++)
{
(*VH)->H[ctr].next = ctr + 1;
}
(*VH)->H[ctr].next = -1;
for(ctr = 0; ctr < max; ctr++)
(*D)->storage[ctr] = -1;
(*D)->nextrung = 0;
}
int myMalloc(VHeap *VH)
{
int temp;
temp = (*VH)->first;
printf("%d\n", temp);
if(temp != -1)
{
(*VH)->first = (*VH)->H[temp].next;
printf("%d ", (*VH)->first);
}
return temp;
}
void myFree(VHeap *VH, int x)
{
int temp;
if(x != -1)
{
(*VH)->H[x].next = (*VH)->first;
(*VH)->first = x;
}
}
int hash(char n[])
{
int ctr, sum = 0;
for(ctr = 0; ctr < strlen(n); ctr++)
sum += (int)n;
return sum % max;
}
void insert(DDS *D, VHeap *VH, int NOP)
{
int ctr;
int x, h;
char n[nam];
printf("Enter the name of the contestant:\n");
for(ctr = 0; ctr < NOP; ctr++)
{
flushall();
gets(n);
x = myMalloc(&(*VH));
h = hash(n);
strcpy((*VH)->H[x].CA.name, n);
(*VH)->H[x].next = (*D)->storage[h];
(*D)->storage[h] = x;
(*D)->ladder[++((*D)->nextrung)] = x;
}
}
void display(DDS D, VHeap VH)
{
int ctr;
for(ctr = 1; ctr <= D->nextrung; ctr++)
puts(VH->H[D->ladder[ctr]].CA.name);
getch();
clrscr();
}
void main(void)
{
DDS D;
VHeap VH;
int NOP;
initialize(&D, &VH);
do
{
printf("How many players are there? ");
scanf("%d", &NOP);
if(NOP < 1 || NOP > 12)
{
printf("You can only input 1 to 12 players");
getch();
}
clrscr();
}while(NOP < 1 || NOP > 12);
insert(&D, &VH, NOP);
display(D, VH);
}
I think the problem is in the myMalloc function. Notice that there are two printf in there. One is for the temp value and one is for the VH-> first value. When I ran the program and input different names, sometimes it goes the way I wanted it to. Sometimes, the value of first suddenly becomes -16384 or any number that is not what I expected. This messes up the arrays causing some undesirable effect. The unexpected numbers comes out randomly depending on the names I inputted or the order of names (e.g.: I inputted the names "Kris" and "Allison" in this order and it goes smoothly. I input "Allison and "Kris" in this order, the value of first after "Kris" becomes -1. It shouldn't be -1 because the program only got 2 virtualheaps).
I don't get this. Please help.