As the subject says: "I don't like doing this but i'm desperate"...I have analyzed my program bit by bit to try to figure out what I am doing wrong, but I haven't been able to find my mistake. It is a simple stack program, with no purpose. The problem is that I can execute the program without any problems, until I try to see the elements of my stack, then it says that there are no elements...which leads me to think that something is wrong in my push function.
Here is the code that I have:
PHP Code:
/* Stack example */
#include <stdio.h>
struct information {
int number;
struct information *next;
};
struct information *first_element; /* points to the first element */
/* function prototypes */
void push(void); /* insert a new item into the stack */
void pop(void); /* remove an existing item from the stack */
void show_stack(void);
int show_menu(void);
int main()
{
int choice;
/* since the list is empty, the first element points to null */
first_element = (struct information *) NULL;
while((choice = show_menu()) != 4)
{
switch(choice) {
case 1: push(); break;
case 2: pop(); break;
case 3: show_stack(); break;
default: printf("Not an element\n"); break;
}
}
}
void push()
{
/* create a pointer to the struct for the new element */
struct information *new_element;
/* obtain memory for the new element, make sure there is enough memory */
new_element = (struct information *) malloc(sizeof(struct information));
if (new_element == NULL) {
printf("\nNot enough memory.");
}
else {
/* obtain new data */
printf("\nWhat number would you like to insert? ");
scanf("%d", &new_element->number);
if(first_element == NULL) {
/* this is the first element being stored */
first_element == new_element;
new_element->next = NULL;
}
else {
/* new_element->next will now point to the element that the first element
used to point to. It ocuppies the first position */
new_element->next = first_element;
first_element = new_element;
}
}
}
void show_stack()
{
struct information *temp;
int i; /* counter */
i = 0;
/* start from the beginning */
temp = first_element;
while(temp != NULL) {
printf("%d -> ", temp->number);
i++;
/* follow the -link- */
temp = temp->next;
}
if(i == 0)
printf("\nThere are no elements in the stack.");
else
printf("\nThere are %d element in the stack", i);
}
int show_menu()
{
int choice;
printf("\n--- Options ---\n"
"1. Push\n"
"2. Pop\n"
"3. Show stack\n"
"4. Exit\n?");
scanf("%d", &choice);
return choice;
}
I have taken out the "pop" function because it is working OK.
I can't find the problem with the "push" function. Please help, I am going mad.
Thanks.