Нет вывода для программы «Связанный список ингредиентов» в C - PullRequest
0 голосов
/ 09 апреля 2020

Я стремлюсь создать связанный список для пищевых ингредиентов из массива символов, хранящегося в файле C (rawRecipies.h). Однако после запуска кода в терминале ничего не появляется. Ранее я столкнулся с ошибкой сегментации. После настройки кода я не получаю вывод.

Я проверял свой код несколько раз и предоставил достаточно места для хранения ингредиентов в моем LinkedList. Тем не менее, я не могу найти источник этой проблемы.

Вы можете заметить, что я добавил несколько точек выхода в коде. Я сделал это для отладки, но они не помогают.

Пожалуйста, дайте мне знать, что не так. Заранее спасибо.

Код ниже:

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

//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;


// struct for storing items from rawRecipies.h
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;

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

        if(strncmp(items->recipe[index], "1", 1) == 0) {
            strcpy(ingredientList[index], (items->recipe[index])+1);
            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);


}

Как уже упоминалось, rawRecipe.h содержит массив указателей символов. Из этого массива я просто заинтересован в сборе строк с 1 перед ним для моего связанного списка ингредиентов. Это все ингредиенты.

char *rawRecipes[]={
"0Broccoli Coleslaw",
"1olive oil",
"1white vinegar",
"1white sugar",
"1package chicken flavored ramen noodles",
"1broccoli",
"1carrots",
"1green onions",
"1sunflower seeds",
"0Creamy Broccoli Salad",
"1broccoli",
"1red onion",
"1mozzarella cheese",
"1mayonnaise",
"1white sugar",
"1white wine vinegar",
"0Minnesota Broccoli Salad",
"1eggs",
"1broccoli",
"1red onion",
"1green olives",
"1pimentos",
"1mayonnaise",
"1dry mustard",
"1salt",
"1celery seed",
"1dill",
"0Curry Broccoli Salad",
"1broccoli",
"1diced onion",
"1dried cherries",
"1sunflower seeds",
"1mayonnaise",
"1curry powder",
"1cider vinegar",
"1white sugar",
"0Broccoli Buffet Salad",
"1broccoli",
"1red onion",
"1sunflower seeds",
"1raisins",
"1feta cheese",
"1yogurt",
"1mayonnaise",
"1white sugar",
"1lemon juice",
"1salt",
"1pepper",
"0Garlic Broccoli Salad",
"1broccoli",
"1olive oil",
"1pine nuts",
"1rice wine vinegar",
"1vegetable oil",
"1cloves garlic",
"1cayenne pepper",
"1raisins",
"0Alysons Broccoli Salad",
"1broccoli",
"1red onion",
"1raisins",
"1white wine vinegar",
"1white sugar",
"1mayonnaise",
"1sunflower seeds",
"0Broccoli and Ramen Noodle Salad",
"1broccoli coleslaw mix",
"1chicken flavored ramen noodles",
"1green onions",
"1peanuts",
"1sunflower seeds",
"1white sugar",
"1vegetable oil",
"1cider vinegar",
"0Zesty Broccoli and Cauliflower Salad",
"1broccoli",
"1cauliflower",
"1red onion",
"1Italian dressing",
"1sunflower seeds",
"0Mardis Broccoli Salad",
"1broccoli",
"1red onion",
"1jumbo black olives",
"1artichoke hearts",
"1tomatoes",
"1green onions",
"1Italian-style salad dressing",
"0Bops Broccoli Cauliflower Salad",
"1broccoli",
"1cauliflower",
"1Cheddar cheese",
"1red onion",
"1creamy salad dressing",
"1white sugar",
"1white vinegar",
"0Best Baconless Broccoli Salad",
"1broccoli",
"1red onion",
"1dried cranberries",
"1pumpkin seeds",
"1flax seeds",
"1mayonnaise",
"1raspberry vinegar",
"1white sugar",
"1pecans",
"0Broccoli Cauliflower Pepita Salad",
"1broccoli",
"1cauliflower",
"1red bell pepper",
"1onion",
"1pumpkin seeds",
"1mayonnaise",
"1yogurt",
"1red wine vinegar",
"1coconut palm sugar",
"1Dijon mustard",
"1salt",
"0Deli-Style Fresh Broccoli Salad",
"1broccoli",
"1green onion",
"1dried cranberries",
"1mayonnaise",
"1honey",
"1cider vinegar",
"0Broccoli Cauliflower Chickpea Bowl",
"1cashews",
"1broccoli",
"1cauliflower",
"1garlic powder",
"1salt",
"1black pepper",
"1chickpeas",
"1lemon juice",
"1tahini",
"1salt",
"0Broccoli Apple Cranberry Salad",
"1mayonnaise",
"1lemon juice",
"1agave nectar",
"1clove garlic",
"1apple cider vinegar",
"1black pepper",
"1sea salt",
"1broccoli",
"1apple",
"1almonds",
"1carrots",
"1red onion",
"1dried cranberries",
"0Broccoli Mango Salad",
"1ranch dressing",
"1orange juice",
"1horseradish",
"1broccoli",
"1mango",
"1cashews",
"1red onion",
"1mandarin oranges",
"0Asian Pasta Salad with Beef, Broccoli and Bean Sprouts",
"1garlic cloves",
"1soy sauce",
"1rice wine vinegar",
"1sugar",
"1sesame oil",
"1ground ginger",
"1hot red pepper flakes",
"1mayonnaise",
"1vegetable oil",
"1salt",
"1penne pasta",
"1broccoli",
"1carrots",
"1red bell pepper",
"1bean sprouts",
"1green onions",
"1peanuts",
"1cilantro",
"0Easy Broccoli Salad I",
"1broccoli",
"1red onion",
"1raisins",
"1sunflower seeds",
"1yogurt",
"1orange juice",
"1mayonnaise",
"0Minnesota Broccoli Salad",
"1eggs",
"1broccoli",
"1red onion",
"1green olives",
"1pimentos",
"1mayonnaise",
"1dry mustard",
"1salt",
"1celery seed",
"1dill",
"0Delicious Broccoli Cranberry Salad",
"1broccoli",
"1dried cranberries",
"1red onion",
"1chopped celery",
"1mayonnaise",
"1white sugar",
"1rice vinegar",
"1cashews",
"0Fruit and Broccoli Buffet Salad",
"1grapeseed oil",
"1granulated sugar",
"1cider vinegar",
"1lime juice",
"1lime zest",
"1garlic",
"1salt",
"1poppy seeds",
"1paprika",
"1dry mustard",
"1pecans",
"1oranges",
"1broccoli",
"1apple",
"1grapes",
"0Strawberry Broco-Flower Salad",
"1broccoli",
"1cauliflower",
"1carrot",
"1strawberries",
"1slivered almonds",
"1raspberry vinaigrette",
"0Broccoli and Tortellini Salad",
"1cheese-filled tortellini",
"1mayonnaise",
"1white sugar",
"1cider vinegar",
"1broccoli",
"1raisins",
"1sunflower seeds",
"1red onion",
""
};
...