私は OS クラスにいて、単純なスタック プログラムを作成する必要があります (メイン関数は、ユーザーが何を求めているかを判断するだけです)。これが C である必要がなければ、何年も前にこれを行っていたでしょうが、私は C コーディングがあまり得意ではないため、「バグ」があります...これまでのバグは、「 pop」と同じ値をオフにします。(実際には何も飛び出していません)。構造体とポインターが実際にどのように機能するかを理解していないためだと思います。それとも、それほど明白ではないコーディングの間違いですか?
#include <stdio.h>
struct node {
int data;
struct node *next;
struct node *prev;
} first;
void push(int);
void pop();
int main(void)
{
int command = 0;
while (command != 3)
{
printf("Enter your choice:\n1) Push integer\n2) Pop Integer\n3) Quit.\n");
scanf("%d",&command);
if (command == 1)
{
// push
int num;
scanf("%d",&num);
push(num);
}
else
{
if (command == 2)
{
pop();
}
else
{
if (command != 3)
{
printf("Command not understood.\n");
}
}
}
}
return 0;
}
void push (int x)
{
struct node newNode;
newNode.data = x;
newNode.prev = NULL;
newNode.next = &first;
first = newNode;
printf("%d was pushed onto the stack.\n", first.data);
}
void pop()
{
if (first.data == '\0')
{
printf("Error: Stack Empty.\n");
return;
}
printf("%d was popped off the stack.\n", first.data);
first = *(first.next);
first.prev = NULL;
}