#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
/*Define custom functions */
void insertElement();
bool elementExists();
int getNumElements();
/*Create linked list */
struct node {
int number;
int occurence;
struct node *next;
};
/*Call our linked list freqTable */
struct node *freqTable = NULL;
unsigned int numElements = 0;
int main(){
int readNumElements = 0;
int i = 0;
int newNum, status;
status = scanf("%d", &readNumElements);
if(status == -1){
fprintf(stderr, "%d is not a number\n", readNumElements);
exit(-1);
}
for (i = 0; i < readNumElements;i++) {
status = scanf("%d", &newNum);
if(status == -1){
fprintf(stderr, "%d is not a number\n", newNum);
exit(-1);
}
if(elementExists(newNum)){
printf("%d exists\n", newNum);
}else{
insertElement(&freqTable, newNum);
}
}
return 0;
}
void insertElement(struct node **list, int n){
struct node *new_input;
new_input = malloc(sizeof(struct node));
if(new_input == NULL){
fprintf(stderr,"Error: Failed to create memory for new node\n");
exit(EXIT_FAILURE);
}
new_input->number = n;
new_input->occurence = 1;
new_input->next = *list;
numElements++;
*list = new_input;
}
bool elementExists(int n){
printf("%d\n", freqTable->number);
return false;
}
int getNumElements(){
return numElements;
}
Ok heres what i got. This should compile.
Problem comes at
if(elementExists(newNum)){
printf("%d exists\n", newNum);
}else{
insertElement(&freqTable, newNum);
}
I get segmentation error and i am not sure why.
In the function
elementExistsyou need to ensure that freqTable is notNULL:Also your
elementExistsdoes not do what its supposed to do(check for existence of a node with valuen), you should do something like: