struct node
{
int id;
float weight;
};
int find_last(struct node Prio_Q[])
{
int i = 1;
while (Prio_Q[i].id != -1)
{
i += 1;
}
return i;
}
void initialize_Q(struct node Prio_Q[], int size)
{
int i;
for (i = 0; i < size; i ++)
{
Prio_Q[i].id = -1;
Prio_Q[i].weight = -1;
}
//printf("The queue is %f", Prio_Q[3].weight);
}
void enque_Q(struct node Prio_Q[], struct node node, int size)
{
int i = find_last(Prio_Q);
Prio_Q[i].id = node.id;
Prio_Q[i].weight = node.weight;
printf("The last index is %d\n", i);
heapify_up(Prio_Q, i);
}
void heapify_up(struct node Prio_Q[], int i)
{
if (Prio_Q[i/2].weight > Prio_Q[i].weight)
{
swap_node(Prio_Q,i/2, i);
heapify_up(Prio_Q, i/2);
}
}
void swap_node(struct node Prio_Q[], int i, int j)
{
struct node temp;
temp = Prio_Q[i];
Prio_Q[i] = Prio_Q[j];
Prio_Q[j] = temp;
//printf("smething has been swapped.\n");
}
int main(int argc, char *argv[])
{
struct node node;
struct node Prio_Q[10];
int size = 10;
initialize_Q(Prio_Q, 11);
node.id = 5;
node.weight = 11;
for(int m = 0; m < size+1; m++)
{
printf("The %dth element in Que is %d with weight %f.\n", m, Prio_Q[m].id, Prio_Q[m].weight);
}
}
This is a priority queue I built, but if you test the code, you will see that the queue will automatically add a node to its last index before I actually ask the function to do so.
In the main function, I only made the node to have two values, but I didnt enqueue the node into the priority queue array. the array will automatically add the node to the last index, can anyone help me please?
Thanks in advance.
Welcome to C; the language does not help you avoid array access out-of-bounds, which is a particular problem with your code:
From
main():Note that you’re calling
initialize_Q()with asizeof11. That means yourforloop will cause an array access beyond the end of yourPrio_Qarray:You should probably use a
#define,enum, orconstvariable to store the size of your array in one location. That will drastically reduce the chances of writing little bugs like this.Your
find_last()routine should do some bounds checking on the size of the array. This code should work fine IFF the rest of your code has no bugs. You might as well re-write this function to also ensure it has not walked off the end of the array. (How will it handle a completely-full array? Hint: Poorly. 🙂And for your output (which ought to be in its own function, so you can sprinkle it throughout your program liberally):
Again, you’ve accessed beyond the end of the array, when
m == 10.