Hey everyone, I've already posted a couple days ago regarding a problem I was facing and I was very lucky to have found help in fixing it
That said, I'll ask once again for help. This one returns me a seg. fault error (found out via debugger) whenever i try to call my printQueue function more than once, I'll post a minimal example code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#define DIM_CODA 10
#define DIM 50
typedef struct{
char articolo[DIM];
double prezzo;
char destinatario[DIM];
}Ordine;
struct node{
Ordine data;
struct node* link;
};
typedef struct node Node;
typedef struct{
Node* front;
Node* back;
int cont;
}Queue;
typedef struct{
Node* top;
int cont;
}Stack;
_Bool isQueueEmpty(Queue *);
_Bool isQueueFull(Queue *);
void pushQueue(Queue *, Ordine *);
void printQueue(Queue *);
int main(){
int nValues, i, done, choice = 0;
Ordine ordine[1];
/** START STUFF I CANNOT TOUCH **/
//declaring queue
Queue queue;
queue.front = NULL;
queue.back = NULL;
queue.cont = 0;
/** END STUFF I CANNOT TOUCH **/
while (done != 1){
printf("How many items?\n");
scanf("%d", &nValues);
printf("\n");
getchar();
for (i = 0; i<nValues; i++){
printf("\nInserirt item:\n");
scanf("%[0-9a-zA-Z ]s", ordine[0].articolo);
printf("\nInsert price:\n");
scanf("%lf", &ordine[0].prezzo);
getchar();
printf("\nInsert buyer:\n");
scanf("%[0-9a-zA-Z ]s\n", ordine[0].destinatario);
getchar();
pushQueue(&queue, ordine);
}
printf("wanna print? 1 for yes\n");
scanf("%d", &choice);
if (choice == 1){
printQueue(&queue);
done = 0;
}
}
return 0;
}
_Bool isQueueEmpty(Queue * e) {
if (e == NULL) {
return false;
}
if (e->cont == 0) {
return true;
} else {
return false;
}
}
_Bool isQueueFull(Queue * e){
return e->cont == DIM_CODA;
}
void pushQueue(Queue * e, Ordine * val){
Node * newnode;
if (isQueueFull(e)){
printf("Overflow error.\n");
}
else
newnode = malloc(sizeof(Node));
newnode->data.prezzo = val->prezzo;
strcpy(newnode->data.articolo, val->articolo);
strcpy(newnode->data.destinatario, val->destinatario);
newnode->link = NULL;
if (isQueueEmpty(e)){
e->front = newnode;
e->back = newnode;
}
else{
e->back->link = newnode;
e->back= newnode;
}
e->cont++;
}
void printQueue(Queue * e){
int i;
for (i=0; i<e->cont; e->front = e->front->link, i++){
printf("Articolo: %-24s\tPrezzo: %-24lf\t Destinatario: %-24s\n", e->front->data.articolo, e->front->data.prezzo, e->front->data.destinatario);
}
}
So this code is about the management of a queue in C. It looked like it was going smoothly up until i tried to printQueue my queue more than once. After the first (successful) printf, the second time I call it my program just crashes with a seg. fault