This simple program creates a linked list that has an acronym and its complete phrase. There are two functions:
The first one creates a node and if the list is empty it puts the node in the first place, otherwise it is put at the end of the list
void createNode(struct node **list, char *siglaElem, char *parolaElem) {
struct node *new_node;
new_node = malloc(sizeof(struct node));
strcpy(new_node->sigla,siglaElem);
strcpy(new_node->parola,parolaElem);
new_node->next = NULL;
if (*list == NULL) {
*list = new_node;
} else {
while ((*list) != NULL) {
(*list) = (*list)->next;
}
(*list)->next = new_node;
}
}
The second function scans the entire list.
int scanList(struct node **list, char *siglaElem, char *parolaElem) {
struct node *scroll = *list;
for (; scroll != NULL; scroll = scroll->next) {
if (strcmp(scroll->sigla, siglaElem) == 0) {
if (strcmp(scroll->parola, parolaElem) == 0)
return 1;
else
return 2;
}
}
createNode(list, siglaElem, parolaElem);
return 0;
}
- It returns 1 if it finds the same acronym and phrase in the list
- It returns 2 if it finds a node with the same acronym but a different phrase
- Finally it returns 0 if there is no node with the same acronym in the list, it calls the first function and it creates one.
The main() function
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node {
char *sigla;
char *parola;
struct node *next;
};
int scanList(struct node **list, char *sigla, char *parola);
void createNode(struct node **list, char *siglaElem, char *parolaElem);
int main() {
struct node *first = NULL;
createNode(&first, "SI", "Sistema Informatico");
createNode(&first, "OS", "Operating System");
printf("%d %d\n", scanList(&first, "SI", "Sistema Informatico"), scanList(&first, "OS", "Operating System"));
return 0;
}
I can't understand why I'm getting Segmentation Fault: 11
What I think is that I'm doing something wrong with the loops. Any solution?