Static List with open hashing C - c

Im a begginer developer and i need help!
I have a txt file of 2287 lines
Contains ID (int), Name (string), Number1, Number2, Number3 (all 3 floats).
"
1234 Jose 10 11 12
...
...
"
I need to get the data from this file and implement a Hash table in separate chain WITH static list.
Also needs to have Insert, Remove and Search functions.
I have so many problems until now.
I dont know how to put it with a static list, and before that i cant hash it properly, its all NULLs..
Anyone can help?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define max 2287
int main(){
FILE* fp;
fp = fopen("dados.txt","r");
if (fp==NULL){
printf("Erro na abertura\n");
system("pause");
exit(1);
}
struct aluno{
int matricula;
char nome[30];
float n1,n2,n3;
struct aluno *next;
};
struct aluno aluno[max];
struct aluno *hash[max];
//povoando com os dados
int i=0;
for(i=0;i<max;i++){
fscanf(fp,"%d %s %f %f %f\n", &aluno[i].matricula, &aluno[i].nome, &aluno[i].n1, &aluno[i].n2, &aluno[i].n3);
}
//teste pra ver se o fscanf funcionava
printf("%s %d %f" , aluno[3].nome, aluno[2].matricula, aluno[1].n1);
void inicializa()
{
int i;
for(i = 0; i < max; i++)
hash[i] = NULL;
}
void insere(int valor){
//cria a newAluno com o valor
struct aluno *newAluno = malloc(sizeof(struct aluno));
newAluno->matricula = valor;
newAluno->next = NULL;
//calcula a chave hash
int chave = valor % max;
//checa se esta null
if(hash[chave] == NULL)
hash[chave] = newAluno;
else{
struct aluno *temp = hash[chave];
while(temp->next){
temp = temp->next;
}
temp->next = newAluno;
}
}
int busca(int valor){
int chave = valor % max;
struct aluno *temp = hash[chave];
while(temp){
if(temp->matricula == valor)
return 1;
temp = temp->next;
}
return 0;
}
void print(){
for(i = 0; i < max; i++)
{
struct aluno *temp = hash[i];
printf("hash[%d]-->",i);
while(temp)
{
printf("%d -->",temp->matricula);
temp = temp->next;
}
printf("NULL\n");
}
}
print();
return 0;
}

Related

im trying to read data from a file and disturb them into linked nodes, however, when i check the linked nodes it says it's empty

So what I'm trying to do is read inputs from a file and disturb the input into nodes, after that I link the nodes together so I get a linked list, however, when I check the linked list it says the list is empty, not sure where the problem is but i assume it's something with the nodes not being linked together correctly
this is the code
#include <stdio.h>
#include <stdlib.h>
#include <intrin.h>
#include <string.h>
void Load_bus_information();
void Load_pass_information();
int Assign_passengers_print_buss_information();
int Print_specific_bus_info();
int Print_unmatched_passengers();
int Add_new_passenger();
void Delete_passenger();
int Delete_bus_number();
char source_all[150][150];
char destination_all[150][150];
int id_all [150];
char time_all[250][250];
int date_all [150];
///////////////////////////////////////////////////\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
int bus_number[150];
int bus_date[150];
char bus_time[155][150];
char sourceBus_all[150][150];
char destinationBus_all[150][150];
int capacity[150];
int price[150];
///////////////////////////////////////////////////\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
struct passenger
{
int id_p ;
int date_p ;
char time_p[150] ;
char sour_p[150];
char des_p[150];
struct passenger* Next;
};
struct bus
{
int num ;
int date_b;
char time_b ;
char des_b;
char sour_p;
struct bus* Next;
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void insert(int id2,int date2,char time2[], char sou2[], char dest2[], struct passenger* L );
struct passenger* FindPrevious(int X, struct passenger* L);
struct passenger* IsLast(struct passenger* P, struct passenger* L);
int isEmpty(struct passenger* L);
void Delete(int X, struct passenger* L);
struct passenger *start=NULL;
struct passenger* L;
void PrintList( struct passenger *L);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int main()
{
int task=0;
do
{
printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
printf("1. Load the bus information file. \n");
printf("2. Load the passenger information file. \n");
printf("3. Assign passengers and print assignment information of all busses.\n");
printf("4. Print a specific bus information along with its passengers information (names and IDs).\n");
printf("5. Print unmatched passengers. \n");
printf("6. Add new passenger.\n");
printf("7. Delete passenger.\n");
printf("8. Delete bus number.\n");
printf("9. Exit.\n");
printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
scanf("%d",&task);
switch(task)
{
case 1:
Load_bus_information();
break;
case 2:
Load_pass_information();
break;
case 3:
Assign_passengers_print_buss_information();
break;
case 4:
Print_specific_bus_info();
break;
case 5:
Print_unmatched_passengers();
break;
case 6:
Add_new_passenger();
break;
case 7:
Delete_passenger();
break;
case 8:
Delete_bus_number();
break;
default:
exit(-1);
//}
}
}
while (task!=9);
return 0;
}
//********************************
void insert(int id2,int date2,char time2[], char sou2[], char dest2[], struct passenger* L )
{
struct passenger *temp2 = NULL, *current = NULL, *head = NULL;
// L = head ;
temp2 = (struct passenger*)malloc(sizeof(struct passenger));
// head = NULL; head = (struct passenger*)malloc(sizeof(struct passenger));
temp2->Next=NULL;
temp2->id_p = id2;
temp2->date_p= date2;
strcpy(temp2->time_p, time2);
strcpy(temp2->sour_p, sou2);
strcpy(temp2->des_p, dest2);
temp2->Next = NULL;
// temp2->Next = head->Next;
//head->Next= temp2;
if(head ==NULL)
{
head = temp2;
current = temp2;
}
else
{
current->Next = temp2 ;
current = current->Next ;
}
printf(" %-10d %-10d %-10s %-10s %-10s \n",temp2->id_p, temp2->date_p, temp2->time_p,temp2->sour_p,temp2->des_p);
head = L ;
}
/*
void insert(int id2,int date2,char time2[], char sou2[], char dest2[] , struct passenger **head)
{
//create a new node
struct passenger *temp2 = malloc(sizeof(struct passenger));
temp2->id_p = id2;
temp2->date_p= date2;
strcpy(temp2->time_p, time2);
strcpy(temp2->sour_p, sou2);
strcpy(temp2->des_p, dest2);
temp2->Next= NULL;
if(*head == NULL)
*head = temp2;
printf(" %d %d %s %s %s \n",temp2->id_p, temp2->date_p, temp2->time_p,temp2->sour_p,temp2->des_p);
//if head is NULL, it is an empty list
}*/
struct passenger* FindPrevious(int X, struct passenger* L)
{
struct passenger* P;
struct passenger* S = L -> Next;
P = L;
while(P->Next != NULL && P->Next->id_p != X)
P = P->Next;
S = S->Next;
return P;
}
struct passenger* IsLast(struct passenger* P, struct passenger* L)
{
return P->Next == NULL ;
}
int isEmpty(struct passenger* L)
{
return L->Next ==NULL;
}
void Delete(int X, struct passenger* L)
{
if(!isEmpty(L))
{
struct passenger* P;
struct passenger* temp;
P = FindPrevious(X, L);
if(P!= NULL)
{
temp = P->Next;
P->Next = temp->Next; //bypass delete cell
free(temp);
}
}
}
struct passenger* MakeEmpty(struct passenger* L)
{
L = ( struct passenger *)malloc(sizeof(struct passenger));
if(L == NULL)
printf ("Out of memory!\n");
else
L->Next = NULL;
return L;
}
void Load_bus_information()
{
FILE* file;
char chB;
char Bname[20];
// Opening file in reading mode
file = fopen("busses.txt", "r");
if (NULL == file)
{
("file can't be opened \n");
}
char Bbuf[100] ;
char Btemp[150];
char timeB[145] ;
char Bdestination[150] ;
char Bsource[150] ;
int bus_num, dateB, cap, pr ;
int counter =0;
while (fgets(Bbuf,100,file))
{
bus_num = atoi( strcpy(Btemp,strtok(Bbuf,"#")));
dateB= atoi( strcpy(Btemp,strtok(NULL,"#")));
strcpy(timeB,strtok(NULL,"#"));
strcpy(Bsource,strtok(NULL,"#"));
strcpy(Bdestination,strtok(NULL,"#"));
pr= atoi( strcpy(Btemp,strtok(NULL,"#")));
cap= atoi( strcpy(Btemp,strtok(NULL,"#")));
for(int s=0; s<5; s++)
{
price[s]= pr;
}
for(int s=0; s<5; s++)
{
capacity[s]= cap;
}
for(int s=0; s<5; s++)
{
bus_number[s]= bus_num;
}
for(int s=0; s<150; s++)
{
bus_date[s]= dateB;
}
for(int s=0; s<150; s++)
{
bus_time[counter][s]= timeB[s];
}
for(int s=0; s<150; s++)
{
sourceBus_all[counter][s]= Bsource[s];
}
for(int s=0; s<150; s++)
{
destinationBus_all[counter][s]= Bdestination[s];
}
counter++;
printf("%-10d %-10d %-10s %-15s %-15s %-15d %-15d \n",bus_num, dateB, timeB, Bsource, Bdestination, pr, cap );
}
}
void Load_pass_information()
{
FILE* fout;
char ch;
char fname[20];
// Opening file in reading mode
fout = fopen("passengers.txt", "r");
if (NULL == fout)
{
printf("file can't be opened \n");
}
// Printing what is written in file
char buf[100] ;
char temp[150];
char source[150] ;
char destination[150] ;
char time[150] ;
int date ;
int id ;
int count =0;
// cutting each line in the file and store them in variables
while (fgets(buf,100,fout))
{
id = atoi( strcpy(temp,strtok(buf,"#")));
date= atoi( strcpy(temp,strtok(NULL,"#")));
strcpy(time,strtok(NULL,"#"));
strcpy(source,strtok(NULL,"#"));
strcpy(destination,strtok(NULL,"#"));
//****************
struct passenger * head;
insert(id, date, time, source, destination, L );
}
count++;
fclose(fout);
}
int Assign_passengers_print_buss_information()
{
//passenger * buss_array[100];
}
int Print_specific_bus_info()
{
}
int Print_unmatched_passengers()
{
}
int Add_new_passenger()
{
int add_id, add_date;
char add_time[100],add_source [100], add_destination [100];
printf("please enter the id of the passenger:_");
scanf("%d", &add_id);
printf("please enter the date :_");
scanf("%d", &add_date);
printf("please enter the time:_");
// for (int i = 0;i < 4;i++)
scanf("%s", add_time);
printf("please enter the place to be collected :_");
scanf("%s", add_source);
printf("please enter the destination:_");
scanf("%s", add_destination);
printf("\n");
Load_pass_information();
insert(add_id, add_date, add_time, add_source, add_destination, L );
//Load_pass_information();
printf("\n");
}
void Delete_passenger( )
{
int X;
printf("enter id of the passenger that will be deleted ");
scanf("%d", &X);
Delete( X,L);
Load_pass_information();
}
int Delete_bus_number()
{
struct passenger*L;
PrintList(L);
}
void PrintList( struct passenger *L)
{
struct passenger* P = L;
if( isEmpty(L))
printf("Empty list\n");
else
do
{
P=P->Next;
printf(" %-10d %-10d %-10s %-10s %-10s \n",P->id_p, P->date_p, P->time_p,P->sour_p,P->des_p);
}
while( !IsLast(P, L) );
printf("\n");
}
this is the whole code so you can copy&paste it if you want, now if you press 8 it should not delete, I made it so it tells if the list is empty or not, which in my case it tells me the list is empty when it shouldn't be.
now load_pass is the function that's responsible to read from the file (read a line and pars it) the insert function should take care of the nodes
the data that would be included in the file:
1970111231#12:51#12072015#London#Liverpool
1251222415#01:12#16012015#California#Florida
1255122451#00:15#12052019#Chicago#Arizona
just to clarify when pressing 8 it should print the parsed data, i.e: 1970111231 12:51 12072015 London Liverpool

Item extraction from a list in C

I wrote a function to delete and extract an Item from a list following the usual algorithm for extraction, but while it scans the list it deletes all the items before the searched element.
I am probably missing some pointer being dereferenced but I can't really see where...
Thank you in advance for the help.
Here's the full code.
//DATA STRUCTURE
typedef struct{//EQUIPMENT
int inUse;
object **arrEquip;
}equip;
typedef struct{//PG
char code[MAXL];
char name[MAXL];
char class[MAXL];
equip equip_t;
stats stats_t;
}pg;
typedef struct nodePg theNodePg, *link;
struct nodePg{ //NODE
pg pg_t;
link next;
};
typedef struct{//LIST WRAPPER
link head;
link tail;
int nPg;
}tabPg;
int main(){
tabPg tabPg_t;
tabInv tabInv_t;
int choice;
tabPg_t.head = NULL;
tabPg_t.nPg = 0;
do{
printMenu(&choice);
runSelectedFun(&tabPg_t, &tabInv_t, choice);
}while(choice != 0);
return 0;
}
void runSelectedFun(tabPg *tabPg_t, tabInv *tabInv_t, int choice){
//[...]
pgExtraction(&tabPg_t->head);
//[...]
}
void pgExtraction(link *head){//eliminarlo dalla lista effettivamente
char toBeDeleted[MAXL];
theNodePg deleted;
int flag = 0;
printf("\nInserisci il codice del personaggio da eliminare");
scanf("%s", toBeDeleted);
deleted = extraction(head, toBeDeleted, &flag);
if(flag == 1){
printf("\nPersonaggio %s eliminato con successo!", deleted.pg_t.code);
}
else printf("\nIl codice inserito non ha corrispondenze all'interno della lista PG!\n");
}
theNodePg extraction(link *head, char *code, int *flag){
link *xp,t;
theNodePg deletedPg = {0};
for (xp = head; xp != NULL; xp = &(*xp)->next) {
if (strcmp((*xp)->pg_t.code, code) == 0) {
t = (*xp);
*xp = (*xp)->next;//eliminazione
deletedPg = *t;
free(t);
*flag = 1;
break;
}
}
return deletedPg;
}

Unknown Issue with segmentation fault and linked lists

So I am trying to program a mechanical program.
The program is long but here are the functions that are causing me problems: recherche_noe and creation_noe. No need to bother with the rest.
It's in french so bear with me but the idea is this: first in the main I ask the user the number of noe in lst_noe (which is a list of noe). With creation_noe he makes that while asking the user for info for the structure. Finally recherche_noe returns the noe that I am looking for. All the info is stored in struct maillage which you have other structures inside. Thank you for your help.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*==============================================*/
/* Déclaration des structures */
/*==============================================*/
struct matrice
{
char nom[20];
int n,m;
double **tab;
struct matrice *next;
};
struct element
{
int num;
int n1, n2;
double k;
struct element *next;
};
struct noeud
{
int num;
double u;
double f;
struct noeud *next;
};
struct maillage
{
int nb_noe, nb_elt;
struct noeud *lst_noe;
struct element *lst_elt;
struct matrice *K, *U, *F;
};
typedef struct matrice* matrices;
typedef struct element* elements;
typedef struct noeud* noeuds;
typedef struct maillage* maillages;
char buffer[100];
/*==============================================*/
/* Recherche */
/*==============================================*/
noeuds recherche_noe(maillages mail,int num){
int i;
maillages temp=mail;
while(temp->lst_noe!=NULL){
if(temp->lst_noe->num == num)
return temp;
temp->lst_noe=temp->lst_noe->next;
}
printf("Le noeud recherche n'existe pas");
return temp;
}
elements recherche_elt(maillages mail,int num){
int i;
maillages temp=mail;
while(temp->lst_elt->num != num /*&& temp->lst_elt->next!=NULL*/){
temp->lst_elt=temp->lst_elt->next;
}
if(temp->lst_elt->num != num /*&& temp->lst_elt->next==NULL*/){
printf("L'element recherche n'existe pas");
}else{
return mail->lst_elt;
}
}
/*==============================================*/
/* creation */
/*==============================================*/
matrices creation_noeud(maillages mail){
int i;
for (i=0;i<mail->nb_noe;i++){
noeuds new = (noeuds)malloc(sizeof(struct noeud));
new->num = i+1;
printf("Deplacement du noeud %d: ",i+1);
buffer[0]='\0';
getchar(); //reinitialisation de buffer
scanf("%[^\n]",buffer);
if((int) strlen(buffer)){ //si la taille du buffer différente 0
new->u= (double)atof(buffer);
}
else{
printf("Donner l'effort %d du noeuds",i+1);
scanf("%lf", &new->f);
}
new->next=mail->lst_noe;
mail->lst_noe=new;
}
}
void creation_element(maillages mail)
{
int i;
for (i=0;i<mail->nb_elt;i++){
elements new= (elements)malloc(sizeof(struct element));
new->num=i+1;
printf("Donner le noeud 1 de l'element %d: ",i+1);
scanf("%d", &new->n1);
printf("Donner le noeud 2 de l'element %d: ",i+1);
scanf("%d", &new->n2);
printf("Donner la raideur de l'element %d: ",i+1);
scanf("%lf",&new->k);
new->next= mail->lst_elt;
mail->lst_elt=new;
}
}
matrices creation_mat(int n,int m, char *nom){
int i,j;
matrices new=(matrices)malloc(sizeof(struct matrice));
strcpy(new->nom,nom);
new->n = n;
new->m = m;
new->tab = (double**)malloc((n)*sizeof(double*));
for (i=0; i<n; i++)
new->tab[i] = (double*)malloc((n)*sizeof(double));
for (i=0;i<n;i++) /* mise a zero des composantes */
for (j=0;j<m;j++)
new->tab[i][j] =0;
return new;
}
/*==============================================*/
/* Assemblage */
/*==============================================*/
void assemblage(maillages mail){
int a,b,i,j,k;
mail->K = creation_mat(mail->nb_noe, mail->nb_noe,"K");
mail->U = creation_mat(mail->nb_noe, 1,"U");
for (j=0; j<mail->nb_noe; j++){ //Initialisation de K
for(k=0; k<mail->nb_noe; k++){
mail->K->tab[j][k]=0;
}
}
printf("%d",recherche_elt(mail,i+1)->n1);
for (i=0; i<mail->nb_elt; i++){ // Assemblage matrice K
a = recherche_elt(mail,i+1)->n1-1;
b = recherche_elt(mail,i+1)->n2-1;
mail->K->tab[a][a] +=recherche_elt(mail,i+1)->k;
mail->K->tab[a][b] -=recherche_elt(mail,i+1)->k;
mail->K->tab[b][a] -=recherche_elt(mail,i+1)->k;
mail->K->tab[b][b] +=recherche_elt(mail,i+1)->k;
}
for (i=0; i<mail->nb_noe; i++){ // Assemblage matrice U
mail->U->tab[i][0] = recherche_noe(mail,i+1)->u;
}
}
/*==============================================*/
/* Produit */
/*==============================================*/
matrices produit(matrices mat1,matrices mat2,char *nom){
int i,j,k;
matrices prod;
if(mat1->m!=mat2->n){
printf("Erreur, les matrices ne sont pas compatibles\n\n");
}else{
prod=malloc(sizeof(struct matrice));
strcpy(prod->nom,nom);
prod->next=NULL;
prod->n=mat1->n;
prod->m=mat2->m;
prod->tab= (double **)malloc(prod->n * sizeof(double *));
for (i=0; i<prod->n; i++)
prod->tab[i] = (double *)malloc(prod->m * sizeof(double));
for (i=0;i<prod->n;i++){
for (j=0;j<prod->m;j++){
prod->tab[i][j]=0;
for (k=0;k<mat1->m;k++){
prod->tab[i][j]+=mat1->tab[i][k] * mat2->tab[k][j];
}
}
}
return prod;
}
}
/*==============================================*/
/* Affichage */
/*==============================================*/
void affiche_mat(matrices mats){
int i,j;
printf("Matrice %s de dimensions %d*%d:\n",mats->nom,mats->n,mats->m);
for (i=0;i<mats->n;i++){
for (j=0;j<mats->m;j++){
printf("%s[%d][%d]: %lf\n",mats->nom,i,j,mats->tab[i][j]);
}
}
printf("\n");
}
int main(){
int i;
elements lst_elt;
noeuds lst_noe;
maillages mail=malloc(sizeof(struct maillage));
mail->lst_noe=NULL;
mail->lst_elt=NULL;
printf("Donner le nombre de noeuds voulu: ");
scanf("%d",&mail->nb_noe);
printf("Donner le nombre d'elements voulu: ");
scanf("%d",&mail->nb_elt);
creation_noeud(mail);
creation_element(mail);
printf("%d",recherche_elt(mail,2+1)->n1+45);
assemblage (mail);
produit(mail->K,mail->U,"F");
/*affiche_mat(mail->K);
printf("\n");
affiche_mat(mail->U);
printf("\n");
affiche_mat(mail->F);
printf("\n");*/
}
When walking the linked list, you are altering the contents of the linked list, instead of advancing the temp.
elements recherche_elt(maillages mail,int num){
elements temp;
for (temp = mail->lst_elt; temp; temp = temp->next ) {
if (temp->num == num) return temp;
}
printf("L'element recherche n'existe pas\n");
return NULL;
}
And, after removal of the typedefs, it becomes:
struct element *recherche_elt(struct maillage *mail,int num){
struct element *this;
for (this = mail->lst_elt; this; this = this->next ) {
if (this->num == num) return this;
}
printf("L'element recherche n'existe pas\n");
return NULL;
}
[The same kind of error is reproduced at other places in the code]

c How to insert a element in a sublist

I have a list of products of several categories in the file "Magazzino.txt" here below:
A451XX (codice prodotto)
CAT001 (codice categoria)
PASTA CONF. 1KG
100
99.0
A451XY (codice prodotto)
CAT002 (codice categoria)
MAGLIA LANA
25
6.70
A452XX (codice prodotto)
CAT001 (codice categoria)
SUGO
33
9.99
First I have to read the file and copy all products in a list with the following structure:
typedef struct {
char codP[C];
char codC[C];
char descr[D];
int num;
float costo;
} tipoBaseLista;
typedef struct nodoLista{
tipoBaseLista info;
struct nodoLista *next;
}prodotto;
typedef prodotto *listaP;
I need to copy this list of products in a list of categories such that each category has a sublist with all product that belong to the specific category. The structure of this list of list is:
typedef struct nodoCat{
char codC[C];
struct nodoCat *next;
listaP nodoP; //puntatore al sottonodo prodotto
}categoria;
typedef categoria *listaC;
This is the full code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#define C 8
#define D 64
typedef struct {
char codP[C];
char codC[C];
char descr[D];
int num;
float costo;
} tipoBaseLista;
typedef struct nodoLista{
tipoBaseLista info;
struct nodoLista *next;
}prodotto;
typedef prodotto *listaP;
typedef struct nodoCat{
char codC[C];
struct nodoCat *next;
listaP nodoP;
}categoria;
typedef categoria *listaC;
int carica_lista(char fName[], listaP *l);
void inserimentoProd(listaP *l, tipoBaseLista p);
listaC trovaCategoria(listaC lc, char categoria[]);
void inserimentoSottolista(listaC lc, tipoBaseLista p, listaP *l);
int main() {
char filename[] = "Magazzino.txt";
listaP lista = NULL;
listaC listaCat = NULL;
tipoBaseLista prodotto;
printf("\nNumero prodotti caricati: %d\n", carica_lista(filename, &lista));
if(lista == NULL){
printf("\nLa lista dei prodotti è vuota!\n");
}
while(lista != NULL){
prodotto = lista->info;
if(listaCat == NULL){
listaCat = malloc(sizeof(categoria));
strcpy(listaCat->codC, prodotto.codC);
listaCat->next = NULL;
inserimentoSottolista(listaCat, prodotto, &lista);
}
else{
listaCat = trovaCategoria(listaCat, prodotto.codC);
if(listaCat != NULL){
inserimentoSottolista(listaCat, prodotto, &lista);
}
else{
listaCat = listaCat->next;
inserimentoSottolista(listaCat, prodotto, &lista);
}
}
lista = lista->next;
}
return 0;
system("PAUSE");
}
//read from file
int carica_lista(char fName[], listaP *l) {
tipoBaseLista prodotto;
int n = 0;
char buf[D] = {0};
char scarto[30];
FILE *f;
f = fopen(fName, "r");
if (f == NULL) {
printf("Non e' possibile aprire il file\n");
exit(1);
}
while (!feof(f)) {
fgets(buf, sizeof(buf), f);
sscanf(buf, "%s%s", prodotto.codP, scarto);
fgets(buf, sizeof(buf), f);
sscanf(buf, "%s%s", prodotto.codC, scarto);
fgets(buf, sizeof(buf), f);
strcpy(prodotto.descr, buf);
fgets(buf, sizeof(buf), f);
sscanf(buf, "%d", &prodotto.num);
fgets(buf, sizeof(buf), f);
sscanf(buf, "%f", &prodotto.costo);
inserimentoProd(l, prodotto);
n++;
}
fclose(f);
return n;
system("PAUSE");
}
//to insert product in the list
void inserimentoProd(listaP *l, tipoBaseLista p){
listaP pCorrente = NULL;
listaP pNodo;
listaP pPrec;
pNodo = malloc(sizeof(prodotto));
pNodo->info = p;
pNodo->next = NULL;
if (*l == NULL){
*l = pNodo;
}
else if(strcmp(p.codP, (*l)->info.codP) < 0){
pNodo->next = *l;
*l = pNodo;
(*l)->next = pNodo;
}
else{
pCorrente = *l;
while (pCorrente->next != NULL && strcmp(p.codP, pCorrente->info.codP) > 0){
pPrec = pCorrente;
pCorrente = pCorrente->next;
}
if(strcmp(p.codP, pCorrente->info.codP) < 0){
pNodo->next = pCorrente;
pPrec->next = pNodo;
}
else if(pCorrente->next == NULL) {
pCorrente->next = pNodo;
}
}
}
//To find the category node under which we insert the sublist
listaC trovaCategoria(listaC lc, char categoria[]){
listaC pCorrente = lc;
while(pCorrente != NULL){
if(strcmp(pCorrente->codC, categoria) == 0){
printf("\nCategoria già presente.\n");
return pCorrente;
}
pCorrente = pCorrente->next;
}
return(NULL);
}
//to insert the product in the head of sublist
void inserimentoSottolista(listaC lc, tipoBaseLista p, listaP *l){
printf("\nInserimento nella sottolista\n");
listaP prodotto = malloc(sizeof(struct nodoLista));
prodotto->info = p;
prodotto->next = *l;
*l = prodotto;
lc->nodoP = prodotto;
printf("\nInserimento effettuato\n");
}
There must be some problem in the "inserimentoSottolista" that cause the crash of the program. What could it be?
The problem is here, inside inserimentoSottolista:
listaP prodotto = malloc(sizeof(prodotto));
You need sizeof(prodotto) to be the size of the struct that was declared earlier, i.e. sizeof(struct nodoLista). But you have used the same name for the name of the variable being initialized. In this case, the prodotto in sizeof(prodotto) isn't the struct, but is the variable. So sizeof(prodotto) ends up being the same as sizeof(listaP), which is just the size of a pointer. It's too small, so you aren't allocating enough memory.
You can fix it by changing the variable name so that it doesn't mask the type name, or by using sizeof(struct nodoLista).

C List Segmentation Fault

Hello guys i got a problem while running this code:
trying to run the printf in the comment i got a segfault, also without that i dont see my listed printed ad the function Stampa should do.
Probably i am missing something with pointers
#include <stdio.h>
#include <stdlib.h>
struct nodo { // double linked list
int info;
struct nodo *prec;
struct nodo *succ;
};
typedef struct nodo nodo;
struct nodo *Crealista(void);
void Stampa (struct nodo *nodo);
int main(int argc, const char * argv[]) {
struct nodo *p;
p = Crealista();
// printf("%d",p->succ->info);
Stampa(p);
return 0;
}
// this funct should print the whole list
void Stampa (struct nodo *p) {
while (p->succ != NULL ) {
printf("Value : %d \n", p->info);
p = p->succ;
}
}
// this funct should create list with n members and return a pointer to the first element
struct nodo *Crealista(void) {
struct nodo *p, *primo, *back;
int i, n;
p = NULL;
primo = NULL;
back = NULL;
printf("Numero di elementi: ");
scanf("%d", &n);
printf("inserisci %d numeri interi positivi: ", n);
for (i=0; i<n; i++) {
p = malloc(sizeof(struct nodo));
scanf("%d", &p->info);
p->prec = back;
p->succ = NULL;
back = p;
}
primo = p;
while (primo->prec != NULL) { primo = primo->prec;}
return(primo);
}
Stampa()
Let's look at what we want to do when we print the entire list:
If the current element is valid, then we want to print it.
Then, we want to iterate to the next element, and continue this loop.
That's not what your code does. Your code looks to see if the current element has a successor, and if it does, we print the current element's value.
That function should actually be:
void Stampa (struct nodo *p) {
while (p != NULL ) {
printf("Value: %d\n", p->info);
p = p->succ;
}
}
Crealista()
If you tell Crealista() to create a list of 0 elements, your final while loop will exhibit undefined behavior.
If you tell Crealista() to create a list of less than 2 elements, your commented printf() in main() will cause undefined behavior (if it was uncommented).
Doubly Linked Lists
You never update the value of nodo->succ. You only update the value of nodo->prev. Here's one example of how to do that:
if (p->prec)
p->prec->succ = p;
Putting all of this together
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
struct nodo {
int info;
struct nodo *prec;
struct nodo *succ;
};
typedef struct nodo nodo;
struct nodo *Crealista(void);
void Stampa (struct nodo *nodo);
int main(int argc, const char * argv[]) {
struct nodo *p;
p = Crealista();
Stampa(p);
}
// Print the list
void Stampa (struct nodo *p) {
while (p != NULL ) {
printf("Value: %d \n", p->info);
p = p->succ;
}
}
// Create a list of n elements
struct nodo *Crealista(void) {
int i, n;
struct nodo *p = NULL;
struct nodo *primo = NULL;
struct nodo *back = NULL;
printf("Numero di elementi: ");
scanf("%d", &n);
assert(n != 0);
printf("inserisci %d numeri interi positivi: ", n);
for (i=0; i<n; i++) {
p = malloc(sizeof(struct nodo));
scanf("%d", &p->info);
p->prec = back;
p->succ = NULL;
if (p->prec)
p->prec->succ = p;
back = p;
}
primo = p;
while (primo != NULL && primo->prec != NULL)
primo = primo->prec;
return primo;
}
Which when run...
Numero di elementi: 5
inserisci 5 numeri interi positivi: 1 2 3 4 5
Value: 1
Value: 2
Value: 3
Value: 4
Value: 5
The printf() call you have commented out will always exhibit undefined behavior when p->succ is NULL, as it will be when p points to the last (or only) element of the list. In that case, although the behavior is formally "undefined", it is quite likely to manifest as a segmentation fault.
In stampa add check
while(p!=NULL)
{
printf("Value %d",p->info);
p=p->succ;
}
You are probably accessing it when it is not allocated. Check it this way there is no problem if it reaches a null value also. And initial null value will not cause problem also(if used).
I have modified your code
// this funct should create list with n members and return a pointer to the first element
struct nodo *Crealista(void) {
struct nodo *p, *primo, *back;
int i, n;
p = NULL;
primo = NULL;
back = NULL;
printf("Numero di elementi: ");
scanf("%d", &n);
printf("inserisci %d numeri interi positivi: ", n);
p = (struct nodo *)malloc(sizeof(struct nodo));
scanf("%d", &p->info);
p->prec = back;
p->succ = NULL;
back = p;
for (i=1; i<n; i++) {
p = (struct nodo *)malloc(sizeof(struct nodo));
scanf("%d", &p->info);
p->prec = back;
p->prec->succ=p;
p->succ = NULL;
back = p;
}
primo = p;
while (primo->prec != NULL) { primo = primo->prec;}
return(primo);
}
You are not setting the succ pointer of previous node correctly. That is what causing you the problem. Check now.

Resources