Ошибка сегментации LinkedList при вставке Node в Back - PullRequest
0 голосов
/ 09 апреля 2020

Я новичок в C и пытаюсь создать LinkedList для хранения ингредиентов из массива rawRecipe (помеченного "1"). Тем не менее, я, кажется, получаю ошибку сегментации. Делая некоторую предварительную диагностику c, кажется, что это происходит из функции insertIngredientAtBack, но я не могу точно определить, где. Не могли бы вы сказать мне, что я пропускаю?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

char *rawRecipes[]={

"0Broccoli Coleslaw",

"1olive oil",

"1white vinegar",

"1broccoli",

"0Creamy Broccoli Salad",

"1broccoli",

"1white sugar",

"1red onion",

"1white wine vinegar",

"0Minnesota Broccoli Salad",

"1eggs",

"1broccoli",

"1red onion",

""

};

//ASSUMING THESE LIMITS
#define MAXRECIPES 30 /* max # of recipes */
#define MAXINGREDIENTTYPES 250 /* max # of ingredient types */
#define MAXINGREDIENTS 250 /* max # of ingredients all recipes */
#define MAXCHARS 100 /* max characters for recipe or ingredient*/
#define INGMAX 25 /* max ingredient count per recipe*/

// structure declarations

struct Ingredient {

    char IngName[MAXCHARS];
    char recipe[MAXRECIPES][MAXCHARS]; //unused member for now.
    int recipeNum;
    struct Ingredient* next;

};

typedef struct Ingredient Ingredients;


typedef struct linkedListIngredient {

    Ingredients* head;

} linkedListIngredient;


typedef struct {

    char recipe[MAXINGREDIENTS][MAXCHARS];

} records;


Ingredients* createIngredientNode(char value[]) {

    Ingredients* newNode = (Ingredients*)malloc(sizeof(Ingredients));

    if (newNode != NULL) {
        strcpy(newNode->IngName, value);
        newNode->next = NULL;
        newNode->recipeNum = 0;
        return newNode;
    }

    printf("Failed to create an ingredients node\n");
    exit(1);

}

bool IngredientNodeEmpty(linkedListIngredient* list2) {

    if (list2->head == NULL) {
        return true;
    }

    else {
        return false;
    }
}

// append a struct to the back of LinkedList
bool insertIngredientAtBack(linkedListIngredient* list2, char value[]) {

    Ingredients* current = list2->head;

    if (IngredientNodeEmpty(list2)) {
        list2->head = createIngredientNode(value);
        return true;
    }

    else {
        while (current->next != NULL) {
            current = current->next;
        }
        current->next = createIngredientNode(value); 

        if (current->next != NULL) {
            return true;
        }

        else {
            printf("Failed to add Ingredient at back\n");
            exit(1);
        }
    }
}



void convertInputToDataStructure(linkedListIngredient* list2, records* items){


    char ingredientList[MAXINGREDIENTTYPES][MAXCHARS];
    int index;
    int globalIndex;

    // Code to find Ingredients and store them in ingredientList.
    for(index = 0, globalIndex = 0; (strcmp(items->recipe[globalIndex],"") != 0); globalIndex++) {

        if(strncmp(items->recipe[globalIndex], "1", 1) == 0) {
            strcpy(ingredientList[index], (items->recipe[globalIndex])+1);
            printf("%s\n", ingredientList[index]);
            index++;

        }   
    }

    printf("%d\n", index);
        // creating a  duplicated Ingredient LinkedList:
    int i;
    for (i = 0; i < index; i++) {
        // evaluating and checking the function to add LinkedList for Ingredient
        insertIngredientAtBack(list2, ingredientList[i]);
    }
}


void ListAllIngredients(linkedListIngredient* list2) {

    Ingredients* current = list2->head;

    int counter = 1;

    while(current->next != NULL) {

        printf("Ingredient #%d: %s\n", counter, current->IngName);
        counter++;
        current = current->next;
    }

    printf("Recipe #%d: %s\n", counter, current->IngName);

}


int main(void) {

    // instantiating the structures for linkedlist access
    linkedListIngredient list2;

    // holds database for ingredients and recipes
    records items;

    // copying all values from rawRecipies.h
    int i;
    for(i = 0; (strcmp(rawRecipes[i], "") != 0); i++) {
        strcpy(items.recipe[i], rawRecipes[i]);
    }

    // first move data from rawRecipes.h to a data structure
    convertInputToDataStructure(&list2, &items);

    ListAllIngredients(&list2);


    return 0;

}

...