I would prefer if more experienced users could give pointers on how I can optimize and think better when writing code.
Using Homework Questions as reference, as this is a homework related question. This should fall into the second category. I know the code is working and that no memory is leaking. The implementation nor the queue.h
can not be changed.
queue.h
:
#define MAX_PRIO 100
typedef const char Datatyp;
#ifndef QUEUE_H
#define QUEUE_H
struct Qelement { // type of a queue
struct Qelement *next; // pointer to next element
int prio; // order in queue
Datatyp *dataptr; // pointer to data
};
typedef struct Qelement *Queue;
queue.c
: (This is were feedback is wanted)
// creating an empty queue
Queue new_queue ()
{
Queue q = (Queue)malloc(sizeof(struct Qelement));
q->next = NULL;
q->prio = MAX_PRIO;
q->dataptr = NULL;
return q;
}
// adding a new element to queue based on priority
// higher priority means earlier in queue
void add (Queue q, int priority, Datatyp *d)
{
// initiation
Queue previous = q;
Queue element = (Queue)malloc (sizeof(struct Qelement));
Queue tmp = NULL;
while (priority <= previous->prio)
{
if (previous->next != NULL)
{
tmp = previous;
previous = previous->next;
}
else if (tmp != NULL)
{
tmp = previous;
previous = previous->next;
break;
}
else
{
break;
}
}
element->prio = priority;
element->dataptr = d;
if (tmp == NULL)
{
element->next = NULL;
previous->next = element;
}
else
{
element->next = previous;
tmp->next = element;
}
}
The code is then used along these lines. (This part can not be changed)
int main () {
const char *daniel = "Daniel";
const char *lisa = "Lisa";
const char *a[] = {"Kalle", "Olle", "Eva", lisa, "Stina",
"Peter", "Anna", daniel, "Johan", "Maria"};
Queue q = new_queue();
int i;
for (i=0; i<10; i++) {
add(q, i%4, a[i]);
}
}
typedef const char Datatyp;
Datatyp... is that a typo, or something you can't change? – Corbin Feb 12 at 21:17enqueue
and to remove is calleddequeue
. These are analogous to thepush
andpop
conventions of a stack. – Roger Feb 12 at 21:27typedef struct Qelement *Queue;
To hide a pointer behind a typedef is considered very bad practice, because it makes the program bug-prone and hard to read. If this comes from your teacher, be aware that they are teaching you bad programming practice... – Lundin Feb 13 at 8:50