Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
89 views
in Technique[技术] by (71.8m points)

c - Why is function exiting if the initial input is -1?

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

/*EVERYTHING WORKS EXCEPT FOR INITIAL -1*/

// Implementing a Node Structure - This represents a node of data
typedef struct _listnode
{
    int item; // Data
    struct _listnode *next; // Linkage
} ListNode;

// Core Functions of a Linked List
void printList(ListNode *head);
ListNode* findNode(ListNode *head, int index);
int insertNode(ListNode **ptrHead, int index, int value);
void removeNode(ListNode **ptrHead, int index);


int main()
{
    // Instantiate a Linked List
    ListNode *head = NULL, *temp;
    /*
    head is a pointer variable that will eventually point to the firstNode.
    temp is a pointer variable that points to the lastNode. This is used in from Linked List functions.
    */
    int num_to_store;
    printf("Enter an Integer to Store (-1 to end):
");
    scanf("%d", &num_to_store);

    while (num_to_store != -1)
    {
        // Initialize a Linked List
        if (head == NULL)
        {
            head = malloc(sizeof(ListNode));
            temp = head;
        }
        else
        {
            temp->next = malloc(sizeof(ListNode));
            temp = temp->next;
        }
        temp->item = num_to_store;
        printf("Enter an Integer to Store (-1 to end):
");
        scanf("%d", &num_to_store);
    }
    temp->next = NULL;

    // Menu-Driven Application
    int user_choice, index, value, *p, option_3;
    puts("");
    printf("----------------
 1: printList()
 2: findNode()
 3: insertNode()
 4: removeNode()
-1: End
----------------
");
    scanf("%d", &user_choice);
    while (user_choice != -1)
    {
        switch(user_choice)
        {
        case 1:
            printList(head);
            break;
        case 2:
            printf("Enter index to search:
");
            scanf("%d", &index);
            p = findNode(head, index);
            if (p != NULL) printf("Node Item: %d
", *p);
            break;
        case 3:
            printf("Enter index to insert:
");
            scanf("%d", &index);
            printf("Enter value to insert:
");
            scanf("%d", &value);
            option_3 = insertNode(&head, index, value);
            if (option_3 == 0) printf("NODE INSERTED!
");
            break;
        case 4:
            printf("Enter index to remove:
");
            scanf("%d", &index);
            removeNode(&head, index);
            break;

        }

        // Prompt User to Make Another Selection
        puts("");
        printf("----------------
 1: printList()
 2: findNode()
 3: insertNode()
 4: removeNode()
-1: End
----------------
");
        scanf("%d", &user_choice);

    }

    return 0;
}

void printList(ListNode *head)
{
    // Linked List is Empty
    if (head == NULL)
    {
        printf("LINKED LIST IS EMPTY!
");
    }

    // Linked List is Not Empty
    else
    {
        printf("LINKED LIST: ");
        while (head != NULL)
        {
            printf("%d ", head->item);
            head = head->next;
        }
        puts("");
    }
}

ListNode* findNode(ListNode *head, int index)
{
    // Linked List is Empty or Index is Invalid
    if (head == NULL || index < 0)
    {
        printf("INVALID!
");
        return NULL;
    }

    // Linked List is not Empty, Check if Index > len(Linked List)
    else
    {
        while (index > 0)
        {
            head = head->next;
            if (head == NULL)
            {
                printf("INVALID!
");
                return NULL;
            }
            index--;
        }
        printf("INDEX FOUND!
");
        return head;
    }
}

int insertNode(ListNode **ptrHead, int index, int value)
{
    ListNode *cur, *pre;
    // Linked List is Empty || Insert at Index 0
    if ((*ptrHead) == NULL || index == 0)
    {
        cur = *ptrHead;
        *ptrHead = malloc(sizeof(ListNode));
        (*ptrHead)->item = value;
        (*ptrHead)->next = cur;
        return 0;
    }
    // Insert in the Middle
    else
    {
        pre = findNode(*ptrHead, index-1);
        if (pre != NULL)
        {
            cur = pre->next; // This is temporary
            pre->next = malloc(sizeof(ListNode)); // L connects to nN
            pre->next->item = value;
            pre->next->next = cur; // nN connects to R
        }
        return 0;
    }
    return -1;
}

void removeNode(ListNode **ptrHead, int index)
{
    ListNode *cur, *pre;
    // Linked List is Empty
    if ((*ptrHead == 0) || index < 0)
    {
        printf("INVALID!
");
    }

    // Remove firstNode
    else if (index == 0)
    {
        cur = findNode(*ptrHead, index);
        *ptrHead = cur->next;
        free(cur); // Unallocate the memory
    }

    // Remove Middle
    else
    {
        pre = findNode(*ptrHead, index-1);
        cur = findNode(*ptrHead, index);
        pre->next = cur->next;
        cur->next = NULL;
    }
}

Hi all, I am writing a Linked List program in C with the 4 core functions. The functions and everything else works except for when I compile the code and type -1. The program exits. I wonder what is wrong. I tried debugging on code::blocks but nothing showed up.

What am I trying to achieve?

  1. Create a Linked List with no nodes.
  2. Code the 4 core functions of a Linked List (insert/remove/print/search).

What have I tried?

  1. Scattering printf() statements to debug.
  2. Checked on stackoverflow for similar problems.
  3. Viewed the code on geeksforgeeks.

Any idea the cause of the problem might be? And any possible solutions for this type of problem?

question from:https://stackoverflow.com/questions/65680112/why-is-function-exiting-if-the-initial-input-is-1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you type -1, the whole while (num_to_store != -1) loop will be skipped, and temp will remain uninitialized, that will make temp->next = NULL; invoke undefined behavior.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...