#Enqueue & Dequeue logical error

1 messages · Page 1 of 1 (latest)

tired stump
#

typedef struct person{
char firstname[30], lastname[30], sex[10];
int hfeet, hinches;
float weight;
}Person;

typedef struct node *nodeptr;

typedef struct node{
Person data;
nodeptr next;
}Node;

void Enqueue(nodeptr *queue, nodeptr *element, nodeptr *tail) {
if (*tail == NULL) {
*queue = *element;
*tail = *element;
}
else {
(*tail)->next = *element;
*tail = *element;
}
}

nodeptr Dequeue(nodeptr *queue, nodeptr *head, nodeptr *tail) {
if (*head == NULL){
nodeptr current = *queue;
*head = NULL;
*tail = *head;
*queue = *head;
return current;
}
else{
nodeptr current = *queue;
*queue = (*queue)->next;
*head = *queue;
return current;
}
}

So here's my code for my enqueue and dequeue function. Problem is, when I add another element, it won't be stored in the queue. What's wrong?

cosmic trellisBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

wild ermine
#

Did you try debugging?

tired stump
#

Yes, I tried debugging both functions and both works. But I don't know why queue wont be updated about the new element

wild ermine
#

If it's not doing what you want it's not working.

#

Debugging is not just about that though. If you don't know how to debug find a tutorial.

sweet umbra
#

Any chance you can repost your code, but this time inside a code block?
Reason being that '*' (for a pointer) in plain text just italicises the text, as you can see.

cosmic trellisBOT
#
How to Format Code on Discord
Markup

```c
int main() {}
```

Result
int main() {}
tired stump
sweet umbra
#

That is a lot of code.
If you need me to look at it, then it will have to be a little later.

sweet umbra
#

Not seriously looked yet, but something leaps out

fflush(stdin);

That's UB.

#

And momentarily jumping into pedantic mode...
You should not be using gets(). It's unsafe and deprecated.
I'd be surprised if your compiler isn't flagging this to you.

#

You could minimise code further and make it safer/better

printf("\nEnter First Name: ");
fgets(element->data.firstname, 30, stdin);

Straight into the record. No need to copy strings about.

Downside is: fgets() leaves the newline in the string, so perhaps follow up with

element->data.firstname[strcspn(element->data.firstname, "\n")] = 0;

You may be doing that quite a bit, so perhaps a macro is called for

#define TRIM_NEWLINE(str) str[strcspn(str, "\n")] = 0

So the code above could be re-written as

printf("\nEnter First Name: ");
fgets(element->data.firstname, 30, stdin);
TRIM_NEWLINE(element->data.firstname);
safe laurel
#

Quick reminder to turn on helper tools while debugging:

-Wall -Wextra -Wpedantic -g3 -Og -fsanitize=address,undefined