1

Here's my code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct Person {
    char *name;
    struct Person *next;
} Person;

typedef struct EscalatorQueue {
    Person *head;
    Person *tail;
} EscalatorQueue;

EscalatorQueue *create_queue() {
    EscalatorQueue *queue = malloc(sizeof(EscalatorQueue));
    queue->head = NULL;
    queue->tail = NULL;
    return queue;
}

void add_person(EscalatorQueue *queue, char *name) {
    Person *person = malloc(sizeof(Person));
    person->name = malloc(strlen(name) + 1);
    strcpy(person->name, name);
    person->next = NULL;
    if (queue->tail == NULL) {
        queue->head = person;
        queue->tail = person;
    } else {
        queue->tail->next = person;
        queue->tail = person;
    }
}

char *remove_person(EscalatorQueue *queue) {
    if (queue->head == NULL) {
        return NULL;
    }
    char *name = queue->head->name;
    Person *temp = queue->head;
    queue->head = queue->head->next;
    if (queue->head == NULL) {
        queue->tail = NULL;
    }
    free(temp);
    return name;
}

int main() {
    EscalatorQueue *queue = create_queue();

    int choice;
    char name[100];
    while (1) {
        printf("Enter 1 to add a person, 2 to remove a person, or 0 to exit: ");
        scanf("%d", &choice);
        switch (choice) {
            case 0:
                return 0;
            case 1:
                printf("Enter the name of the person: ");
                scanf("%s", name);
                add_person(queue, name);
                break;
            case 2:
                char *removed_name = remove_person(queue);
                if (removed_name == NULL) {
                    printf("Queue is empty\n");
                } else {
                    printf("%s was removed from the queue\n", removed_name);
                    free(removed_name);
                }
                break;
        }
    }
}

When I compile my code in DEV C++ I'm getting an error in the case 2: of the switch statement, on this line:

char *removed_name = remove_person(queue);

However, when compiling this code on the online compilers, I get no error.

So, what mistake have I made and how can I fix it?

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Gurunath
  • 11
  • 3
  • You did not show the error message. When asking about a compilation error, quote the exact text of the compiler error message. Also, reduce the code to a [mre]. Not only could you have reduced the code by removing cases 0 and 1, you could have removed the custom types and other function definition and reduced this to `int main(void) { switch (2) { case 2: char *removed_name; } }`. Do not just dump your program on Stack Overflow; do preliminary work to reduce it to the essential part of the problem, to save other people work and to serve as a clear simple example for future users. – Eric Postpischil Jan 05 '23 at 11:25

0 Answers0