我遇到了细分错误,运行后可能还有更多错误,但是由于这个原因,我现在无法检查其他任何内容。

该程序应该像这样工作:


用户输入5个数字时,应按升序打印
如果用户输入的数字已经退出,则删除原始值
如果用户输入一个本机值,请向后打印列表


到目前为止,这是我的代码:

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

struct element {
int i;
struct element *next;
};

void insert (struct element **head, struct element *new)
{

struct element *temp;
temp = *head;

while(temp->next != NULL)
{
    if((*head==NULL))
    {
    head = malloc(sizeof(struct element));
    //temp->i = i;
    temp->next = new;
    new = temp;
    }
    else if(temp->i == new->i)
    {
        new = malloc(sizeof(struct element));
        free(new);
        //purge(&head,&new);

    }
    else if(temp->i < new->i)
    {
        temp->i = new->i;
    }
    else if(temp->i > new->i)
    {
        new = new->next;
    }
}

}

void purge (struct element *current, struct element *predecessor)
{

predecessor->next = current -> next;
free(current);
}

void printList (struct element *head)
{
while(head)
{
    printf("%d", head -> i);
    head = head->next;
}

}

void printListBackwards (struct element *ptr)
{
if(ptr == NULL)
{
    printf("list is empty \n");
    return;
}
if(ptr->next != NULL)
{
    printListBackwards(ptr->next);
}
printf("print %p %p %d\n", ptr, ptr->next, ptr->i);
}


int main()
{
int n = 0;
int count = 5;
printf("enter a Number: \n");
scanf("%d",&n);
struct element *new;
new = malloc(sizeof(struct element));
struct element *head = NULL;
new->i = n;
while(count!=0)
{
    insert(&head,new);
    printList(head);
    count++;
}

}

最佳答案

main()函数中,您只能使用malloc()分配和创建一个元素;然后,您尝试将其添加到列表中5次。这将引起混乱。您应该为添加到列表中的每个元素分配一次节点。

struct element *head = NULL;

while (count!=0)
{
    printf("enter a Number: \n");
    if (scanf("%d", &n) != 1)
        break;
    struct element *new = malloc(sizeof(struct element));
    if (new == 0)
        break;
    new->i = n;
    new->next = NULL;
    insert(&head, new);
    printList(head);
    count--;
}


请注意,修订后的代码将同时检查scanf()malloc()的结果。它还将新元素的next指针设置为NULL。它倒数而不是倒数;这可能会占用更少的内存。

我没有对此进行测试,因此可能存在(很可能还有)其他问题,但这可能会更好(修复一些问题,但不是所有问题)。

您确实需要学习如何使用调试器,至少要足够了解堆栈跟踪,才能知道导致崩溃的代码行。

关于c - 我在C中存在段错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15823880/

10-14 18:36
查看更多