I have to create a list where each node contains the information of a game. Data are acquired by keyboard. So I have to create an insert function(inserisciTestaLista) in the list,but when I run the program stops. I have no compilation errors.
This's output:
...\Debug\progetto1.exe (processo 7356) terminato. Codice restituito: -1073741819.
Premere un tasto qualsiasi per chiudere questa finestra...
this's the code
#include <stdio.h>
#include <stdlib.h>
typedef struct s_partita {
char team1[32], team2[32];
int set1, set2;
char data[11];
}t_partita;
typedef struct nodo {
t_partita info;
struct nodo *next;
}t_nodo, *lista;
void inserisciTestaLista(lista *L, t_partita partita) {
lista aux;
aux = (lista)malloc(sizeof(t_nodo));
if (aux == NULL)
exit(1);
aux->info = partita;
aux->next = *L;
*L = aux;
}
int main() {
int scelta = 0;
lista L = NULL;
t_partita partita;
do {
printf("*****************MENU**************\n");
printf("0. ESCI\n");
printf("1. inserisci partita\n");
printf("2. stampa lista\n");
scanf("%d", &scelta);
switch (scelta) {
case 1: {
printf("Inserisci team 1: ");
scanf("%s", partita.team1);
printf("Inserisci team 2: ");
scanf("%s", partita.team2);
printf("Inserisci punteggio (esempio 3-1): ");
scanf("%d%d", &partita.set1, &partita.set2);
printf("Inserisci data (esempio 2020-01-01): ");
scanf("%s", partita.data);
inserisciTestaLista(L, partita);
break;
}
case 2: {
break;
}
}
} while (scelta != 0);
}
You can pass the memory address from the list in line 49.
inserisciTestaLista(&L, partita);
Related
So, I was trying to write this program in which it should be possible to create a dynamic list in which are stored data about some cars (model, colour, year) and then it should be possible to view a list of all of them. There are no errors in the program, and no segmentation fault, however as soon as I try to visualize the list, I get no output. I tried using GDB to debug it, and the struct pointer doesn't actually get any data during the input. Here is the whole code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node{
char modello[81];
char colore[81];
int anno;
struct node *next;
};
typedef struct node car;
car* insertNode(car* head);
car* destroyer(car* head);
void visualizer(car *head);
int main(){
car *head = NULL;
int n,tasto;
char option,enter;
do{
printf("Premere 1 per inserire un nuovo veicolo nel catalogo.\n");
printf("Premere 2 per visualizzare l'intero catalogo.\n");
printf("Premere qualsiasi altro tasto per uscire.\n\n");
scanf("%i",&tasto);
switch (tasto){
case 1:
insertNode(head);
break;
case 2:
visualizer(head);
break;
default:
break;
}
}while(tasto==1||tasto==2);
if(head!=NULL)
head=destroyer(head);
printf("Uscita.\n");
return 0;
}
car* insertNode(car *head){
car *temp;
car *prec;
temp=(car *)malloc(sizeof(car));
if(temp!=NULL){
temp->next=NULL;
if(head==NULL)
head=temp;
else{//Raggiungi il termine della lista
for(prec=head;(prec->next)!=NULL;prec=(prec->next));
prec->next=temp;
}
printf("Inserire il modello dell'auto: ");
scanf("%s",&temp->modello);
printf("Inserire il colore dell'auto: ");
scanf("%s",&temp->colore);
printf("Inserire l'anno di immatricolazione dell'auto: ");
scanf("%i",&temp->anno);
printf("\n");
}
else
printf("Memoria esaurita!\n");
return head;
}
void visualizer(car* head){
car *temp;
int i=1;
temp=head;
while(temp!=NULL){
printf("Auto numero %i:\n",i);
printf("Modello: %s.\n",temp->modello);
printf("Colore: %s.\n",temp->colore);
printf("Anno di immatricolazione: %i.\n",temp->anno);
printf("\n");
i++;
temp=temp->next;
}
}
car *destroyer(car* head){
car *temp;
while(head!=NULL){
temp=head;
head=head->next;
free(temp);
}
return NULL;
}
Can someone please explain why this happens? I have no clue about what's wrong with this.
The first error is in the do while, when you are at about line 31 in the case switch you don't store the return of the insert function anywhere. Here it is the fixed code:
do{
printf("Premere 1 per inserire un nuovo veicolo nel catalogo.\n");
printf("Premere 2 per visualizzare l'intero catalogo.\n");
printf("Premere qualsiasi altro tasto per uscire.\n\n");
scanf("%i",&tasto);
switch (tasto){
case 1:
head=insertNode(head);
break;
case 2:
visualizer(head);
break;
default:
break;
}
}while(tasto==1||tasto==2);
The second error is when you are getting the value from keyboard in insert node.
You are using the "&" operator when you already have the address of the array you want to fill, because you are indeed working with arrays. Here you can see the fixed code:
car* insertNode(car *head){
car *temp;
car *prec;
temp=(car *)malloc(sizeof(car));
if(temp!=NULL){
temp->next=NULL;
if(head==NULL)
head=temp;
else{//Raggiungi il termine della lista
for(prec=head;(prec->next)!=NULL;prec=(prec->next));
prec->next=temp;
}
printf("Inserire il modello dell'auto: ");
scanf("%s",temp->modello);
printf("Inserire il colore dell'auto: ");
scanf("%s",temp->colore);
printf("Inserire l'anno di immatricolazione dell'auto: ");
scanf("%i",&temp->anno);
printf("\n");
}
else
printf("Memoria esaurita!\n");
return head;
}
I'm trying to arrange the linked list data by name so I'm comparing each node name with the next one. and yes want to swap nodes data, to have a linked list arranged by name.
I've tried to swap each data of node with the other in case the test in function "trier" is true the test is (strcmp(prec, ptr) < 0). it seems working well until the last one.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
struct patient {
int cin;
char nom[8];
char prenom[8];
int annee;
struct patient *suivant;
};
struct patient *tete = NULL;
void creationdePatient() {
struct patient* ptr;
char rep;
ptr = malloc(sizeof(struct patient));
tete = ptr;
printf("Saisir Numero de Cin de Nouveau Patient: ");
scanf("%d", &tete->cin);
printf("Saisir Nom de Patient: ");
scanf("%8s", &tete->nom);
printf("Saisir prenom de Patient: ");
scanf("%8s", &tete->prenom);
printf("Saisir annee de naissance de Patient: ");
scanf("%d", &tete->annee);
tete->suivant = NULL;
printf("\nVoulez vous Saisir un autre Patient ?: (O,N): \n");
scanf(" %c", &rep);
while (toupper(rep) == 'O') {
ptr = malloc(sizeof(struct patient));
printf("Saisir Numero de Cin de Nouveau Patient: ");
scanf("%d", &ptr->cin);
printf("Saisir Nom de Patient: ");
scanf("%8s", &ptr->nom);
printf("Saisir prenom de Patient: ");
scanf("%8s", &ptr->prenom);
printf("Saisir annee de naissance de Patient: ");
scanf("%d", &ptr->annee);
ptr->suivant = tete;
tete = ptr;
printf("\nVoulez vous Saisir un autre Patient ?: (O,N): \n");
scanf(" %c", &rep);
}
}
void echangedeNom(struct patient *x, struct patient *y) {
char temp[8];
strcpy(temp, y->nom);
strcpy(y->nom, x->nom);
strcpy(x->nom, temp);
}
void echangedePrenom(struct patient *x, struct patient *y) {
char temp[8];
strcpy(temp, y->prenom);
strcpy(y->prenom, x->prenom);
strcpy(x->prenom, temp);
}
void echangedesentiers(struct patient *x, struct patient *y) {
int temp = 0;
temp = y->cin;
y->cin = x->cin;
x->cin = temp;
}
void echangedesannes(struct patient *x, struct patient *y) {
int temp = 0;
temp = y->annee;
y->annee = x->annee;
x->annee = temp;
}
void printtList() {
struct patient *temp = tete;
while (temp != NULL) {
printf("Cin: %d | Nom:%s | Prenom: %s |Anne de naissance: %d\n",
temp->cin, temp->nom, temp->prenom, temp->annee);
temp = temp->suivant;
}
}
void trier() {
struct patient *ptr = tete;
struct patient *prec = NULL;
int echange;
do {
echange = 0;
while (ptr != NULL && ptr->suivant != NULL) {
prec = ptr;
ptr = ptr->suivant;
if (strcmp(prec->nom, ptr->nom) < 0) {
echangedeNom(prec, ptr);
echangedePrenom(prec, ptr);
echangedesentiers(prec, ptr);
echangedesannes(prec, ptr);
echange = 1;
}
}
} while (echange == 1);
}
int main() {
creationdePatient();
printtList();
trier();
printf("=======================\n");
printtList();
}
some data while swapping get the wrong information like the cin number after swapping is not the same anymore.
You are swapping twice an integer here:
while(ptr!=NULL && ptr->suivant!=NULL){
// [...]
echangedesentiers(prec,ptr);
echangedesentiers(prec,ptr);
// [...]
}
By the way, here is a first step to learn to debug your code : How to debug small programs.
i have a problem with adding an string type inside of a node list.
I am using the command strncpy(), but i am not sure how this works with the pointer.
This is the code block i have now.
My specific problem is in the function "Insertar" because it expects a type char *variable but i an inserting just a char.
#ifndef _LINK_LIST_H_
#define _LINK_LIST_H_
#include <stdio.h>
typedef struct
{
int dia;
int mes;
int ano;
}fecha;
struct NODEL
{
float valor;
char variable [10];
int resol;
fecha f;
struct NODEL* nextNode;
};
typedef struct NODEL LISTNODE;
typedef LISTNODE * LISTNODEPTR;
void insertar(LISTNODEPTR * lista, float newvalor, char *variable, int newresol,
#endif
void insertar(LISTNODEPTR * lista, float newvalor, char *variable, int newresol, int newdia, int newmes, int newano)
{
LISTNODEPTR newPtr, prevPtr, currPtr;
newPtr = malloc(sizeof(LISTNODE));
if(newPtr != NULL)
{
newPtr->valor = newvalor;
strncpy(newPtr->variable,newPtr->variable,10);
newPtr->resol = newresol;
newPtr->f.dia = newdia;
newPtr->f.mes = newmes;
newPtr->f.ano = newano;
newPtr->nextNode = NULL;
prevPtr = NULL;
currPtr = *lista;
while(currPtr != NULL && newvalor > currPtr->valor)
{
prevPtr = currPtr;
currPtr = currPtr->nextNode;
}
if(prevPtr == NULL)
{
newPtr->nextNode = *lista;
*lista = newPtr;
}
else
{
prevPtr->nextNode = newPtr;
newPtr->nextNode = currPtr;
}
}
else
{
printf("Elemento no insertado, no hay memoria disponible\n");
}
}
int main(void)
{
LISTNODEPTR data_base;
float valorADC;
char varIngresada;
int resolucion;
int diaIng;
int mesIng;
int anoIng;
printf("Valor de ADC: ");
scanf("%f", &valorADC);
fflush(stdin);
printf("Tipo variable 'Presion'/'Temperatura'/'Aceleracion': ");
scanf("%s", &varIngresada);
fflush(stdin);
printf("Resolución: ");
scanf("%d", &resolucion);
fflush(stdin);
printf("Fecha (dia): ");
scanf("%d", &diaIng);
fflush(stdin);
printf("Fecha (mes): ");
scanf("%d", &mesIng);
fflush(stdin);
printf("Fecha (año): ");
scanf("%d", &anoIng);
fflush(stdin);
insertar(&data_base, valorADC, varIngresada, resolucion, diaIng, mesIng, anoIng);
imprimir(data_base);
}
This program is supposed to manipulate a student list. Every time I try to add more than one student I get a segmentation fault error. Also, when I try to print the list recursively I get a segmentation fault error. I think it has to do with how I am saving to the structure and/or calling it. I am very new to programming so I'm sure it is something simple. Any ideas?
//Header file declarations.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//Structure defintion.
struct student {
int ID;
char name[40];
struct student *next;
};
//Type definition.
typedef struct student Student;
//Function prototypes.
int getChoice();
Student *addToList(Student *List);
void printList(Student *List);
void printListRR(Student *List);
void searchList(Student *List);
/*main function
Objective: This function provides runs a function call based on an option selected the user in another function.
Input: This function recieves no input from the user directly but it is passed their menu selection.
Output: The function outputs error messages and a closing salutation to the user. It returns 0.
*/
int main(void) {
int choice = 0;
Student *SLIST = NULL;
//Call getChoice to get user's selection
choice = getChoice();
//Switch-case for the possible menu selections
while(choice >= 0) {
switch(choice) {
case 0 : printf("Bye...\n"); exit(0);
case 1 : SLIST = addToList(SLIST); break;
case 2 : printList(SLIST); break;
case 3 : printListRR(SLIST); break;
case 4 : searchList(SLIST); break;
default: printf("That is not a valid choice\n");
}
choice = getChoice();
}
if(SLIST) free(SLIST);
return 0;
}
int getChoice() {
int choice = 0;
printf("\n****** MENU ******\n");
printf("1. Add new student to list.\n");
printf("2. Print the student list, beginning to end.\n");
printf("3. Recursively print the student list from the end.\n");
printf("4. Search the list for a student.\n");
printf("0. Quit.\n");
printf("\nEnter your choice: ");
scanf("%d", &choice);
return choice;
}
Student *addToList(Student *List){
Student *studentPtr = (Student *) malloc(sizeof(Student));
printf("Student ID: ");
scanf("%d", &(studentPtr->ID));
printf("Student Name: ");
scanf(" %[^\n]", studentPtr->name);
if(List == NULL){
return studentPtr;
}
Student *nextStudent = List;
while (nextStudent->next != NULL){
nextStudent = nextStudent->next;
}
nextStudent->next = studentPtr;
return List;
}
void printList(Student *List){
while(List != NULL){
printf("%d %s\n", List->ID, List->name);
List = List->next;
}
}
void printListRR(Student *List){
if(List == NULL){
return;
}
printListRR(List->next);
}
void searchList(Student *List){
int idSearch;
printf("Enter student ID to search for: ");
scanf("%d", &idSearch);
while(List != NULL){
if(List->ID == idSearch){
printf("%d %s\n", List->ID, List->name);
return;
}
List = List->next;
}
printf("ID %d not found", idSearch);
}
Try initialising studentPtr->next to NULL in addToList()?
In my program,I plan to filter choices for the users to get a specific piece of data for the inventory.
For instance,at start of the program, there will be menu that gives user option to add or delete data and then for instance if they say insert then I will give them option to select a car company(i.e. like Toyota or Honda) and once they select that company I will give them choice of all Toyota models they can add in the inventory.This will happen so I can narrow down and do a selected operation on the information I have been given.
The thing is I don't know how to filter out the models for a specific company.I have created different arrays containing different models but I don't know how to display user option of models for that company.
Here is my code..
#include <stdio.h>
#include <stdlib.h>
#define MAX_WORD_LENGTH 20
#define MAX_SIZE 100
typedef struct cardata{
char carname[MAX_WORD_LENGTH];
char carmodel[MAX_WORD_LENGTH];
char caryear[MAX_WORD_LENGTH];
char cartype[MAX_WORD_LENGTH];
int quantity;
}CarData;
struct node{
CarData data;
struct node *next;
struct node *prev;
}*start=NULL;
const char *companyList[10] = {"Toyota", "Honda","Hyundai","Nissan","Mitsubishi","VoksWagon","Acura","Ford","Dodge","GMC"};
const char *companyModels[10] = {toyotaModels,hondamodels,hyundaimodels,nissanmodels,mitsubishimodels,vokswagonmodels,acuramodels,fordmodels,dodgemodels,gmcmodels};
const char *toyotaModels[10]={"Corolla","Camery"}
const char *hondaModels[10]={"Civic","Accord"};
void insert_first(){
struct node *ptr;
char carname[MAX_WORD_LENGTH];
char carmodel[MAX_WORD_LENGTH];
char caryear[MAX_WORD_LENGTH];
char cartype[MAX_WORD_LENGTH];
int carQuantity;
int ch;
printf("\n\n\n1.Toyota \n2.Honda \n3.Hyundai \n4.Nissan \n5.Mitsubishi \n6.Volksvagon \n7.Acura \n8.Ford \n9.Dodge \n10.GMC\n");
printf("\nPress a number to select corresponding car(i.e. 1 for toyota, 2 for honda): ");
scanf("%d", &ch);
strcpy(carname,companyList[ch-1]);
printf("\n\nEnter the car model: ");
scanf("%s", carmodel);
printf("\n\nEnter the car year: ");
scanf("%s", caryear);
printf("\n\nEnter the car type: ");
scanf("%s", cartype);
printf("\n\nEnter the quantity of models: ");
scanf("%d", &carQuantity);
if(start==NULL){
start=(struct node *)malloc(sizeof(struct node));
strcpy(start->data.carname,carname);
strcpy(start->data.carmodel,carmodel);
strcpy(start->data.caryear,caryear);
strcpy(start->data.cartype,cartype);
start->data.quantity=carQuantity;
start->prev=NULL;
start->next=NULL;
}else{
ptr=start;
start=(struct node *)malloc(sizeof(struct node));
strcpy(start->data.carname,carname);
strcpy(start->data.carmodel,carmodel);
strcpy(start->data.caryear,caryear);
strcpy(start->data.cartype,cartype);
start->data.quantity=carQuantity;
start->next=ptr;
}
}
void delete_first(){
struct node *ptr;
char carname[MAX_WORD_LENGTH];
char carmodel[MAX_WORD_LENGTH];
char caryear[MAX_WORD_LENGTH];
char cartype[MAX_WORD_LENGTH];
char modelNumber[MAX_WORD_LENGTH];
int carQuantity;
if(start==NULL){
printf("\n\nLinked list is empty.\n");
}else{
ptr=start;
printf("\nThe car for which the entry is removed is %s \n",ptr->data.carname);
strcpy(start->data.carname,carname);
strcpy(start->data.carmodel,carmodel);
strcpy(start->data.caryear,caryear);
strcpy(start->data.cartype,cartype);
start->data.quantity=carQuantity;
start=start->next;
free(ptr);
}
}
void display()
{
struct node *ptr=start;
int i=1;
if(ptr == NULL){
printf("\nLinklist is empty.\n");
}else{
printf("\nSr. No Make Model Year Type Quantity\n");
while(ptr != NULL){
printf("\n%d.\t%s %s %s %s %d\n", i,ptr->data.carname,ptr->data.carmodel,ptr->data.caryear,ptr->data.cartype,ptr->data.quantity);
ptr = ptr->next;
i++;
}
}
}
int main(void)
{
int ch;
do
{
printf("\n\n\n1. Insert \n2. Delete \n3. Display \n4. Exit\n");
printf("\nEnter your choice: ");
scanf("%d", &ch);
switch(ch)
{
case 1:
insert_first();
break;
case 2:
delete_first();
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("\n\nInvalid choice. Please try again. \n");
}
} while(1);
return 0;
}
OP: "don't know how to display user option of models."
You need to dynamically form the question from the selected car company. Suggest not using fixed list sizes (drop the 10) and append a NULL to indicated end of list. Improve error handling by checking scanf result and argument range.
const char **CompanyModels[] = { toyotaModels, hondaModels, 0 /* List is 2 long */};
int ModelPrompt(const char **CompanyModels) {
printf("\n\n\n");
int i;
for (i=0; CompanyModels[i], i++) {
printf("%d.%s \n", d+1, CompanyModels[i]);
}
return i;
}
void insert_first(){
...
// recommend replacing next 2 lines with a CompanyPrompt(companyList);
printf("\n\n\n1.Toyota \n2.Honda \n3.Hyundai \n4.Nissan \n5.Mitsubishi \n6.Volksvagon \n7.Acura \n8.Ford \n9.Dodge \n10.GMC\n");
printf("\nPress a number to select corresponding car(i.e. 1 for toyota, 2 for honda): ");
scanf("%d", &ch);
strcpy(carname,companyList[ch-1]);
int MaxModelIndex = ModelPrompt(CompanyModels[ch]);
int carmodelIndex = -1;
if ((1 != scanf("%d", carmodelIndex)) || (carmodelIndex < 0) || (carmodelIndex > MaxModelIndex)) {
; // handle error
}
strcpy(carmodel, CompanyModels[ch][carmodelIndex]);
// continue with similar code for cartype.