Hi all, am currently doing a project from KNKing's C program a modern approach.
3 files involved. queueADT.h, queueADT.c, stackclient.c
code for queueADT.h
Code:
#ifndef QUEUE_H#define QUEUE_H
#include <stdbool.h> /* C99+ only */
typedef int Item;
typedef struct queue_type *Queue;
Queue create(void);
void destroy(Queue s);
void insertend(Queue q, Item i);
void removebegin(Queue q);
Item returnfirst(Queue q);
Item returnlast(Queue q);
bool isempty(Queue q);
#endif
relevant code oif queueADT.c
Code:
//structure
struct queue_type {
Item queue[MAXQUEUESIZE];
int firstemptyslot;
int toberemoved;
int numitems;
};
void insertend(Queue q,Item i) //inserting number into the next slot in array
{
if (q->numitems==100)
queue_overflow();
q->queue[q->firstemptyslot]= i;
q->firstemptyslot++;
q->numitems++;
if (q->firstemptyslot>99)
q->firstemptyslot=0;
}
Queue create(void) //creating pointer to structure
{
Queue q = malloc(sizeof(struct queue_type));
if (q == NULL)
terminate("Error in create: queue could not be created.");
q->firstemptyslot = 0;
q->toberemoved = 0;
q->numitems = 0;
return q;
}
Item returnfirst(Queue q){ //returning first number in the array
if (isempty(q))
queue_underflow();
if (q->firstemptyslot == 0)
return q->queue[q->toberemoved];
}
relevant code of stackclient.c (main). Basically I insert some numbers into the strcuture and get the program to print it back out
Code:
#include <stdio.h>
#include "queueADT.h"
int main(void)
{
Queue s1, s2;
Item n;
s1 = create();
s2 = create();
insertend(s1, 4);
insertend(s1, 8);
printf("First number %d from s1\n", returnfirst(s1));
removebegin(s1);
//etc etc continue printing out numbers
The problem is that my program keeps giving out the number 2, or rather the function that returns a number from the structure in the array keeps returning the number 2, even though I inserted numbers such as 4 or 8 or other numbers.
I have spent quite some time changing things around but I cant figure out what is wrong. Would appreciate any kind help sirs thank you. Apologies if any of the code is formatted badly because I tried changing some code to fix it.