2

执行此操作时出现分段错误,但编译器没有显示任何错误。如果我问的是非常基本的问题,请原谅我,因为我长期以来一直不擅长用 C 进行编码。

这是我的代码:

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

struct link_list {
    int x;
    int y;
    struct link_list *next;
    struct link_list *prev;
};

int inp_sum (int *x, int *y){
        printf("Enter x:");
        scanf("%d",&x);
        printf("Enter y:");
        scanf("%d",&y);
    printf("%d+%d",x,y);
    int z;
    z=*x+*y;
    return z;
}

void main(){
    struct link_list *first_node;
    first_node=malloc(sizeof(struct link_list));
    first_node->next=0;
    first_node->prev=0;

    struct link_list *cur;
    cur = malloc(sizeof(struct link_list));
    while(inp_sum(&cur->x,&cur->y)<100){
        cur->next=malloc(sizeof(struct link_list));
        cur=cur->next;
        cur->next=0;
        cur->prev=0;
    }

    print_llist(first_node);
}

print_llist(struct link_list *root){
    struct link_list *current;
    current=malloc(sizeof(struct link_list));
    current = root;
    while ( current != NULL ) {
        printf( "%d\n", current->x );
        current = current->next;
    }
}

我想要做的是创建一个链接列表节点并在输入总和小于100时扩展链接列表,因为我想将x,y(节点成员)的指针发送到一个函数,该函数在获取后返回它们的总和输入并将输入存储给他们。

但我认为我在传递指针或添加指针时做错了。

问候

4

2 回答 2

1

x并且y已经是指针,所以:

    printf("Enter x:");
    scanf("%d",&x);
    //         ^ address of int *
    printf("Enter y:");
    scanf("%d",&y);

        // ^ int 的地址 *

应该:

    printf("Enter x:");
    scanf("%d",x);
    //         ^ address of int
    printf("Enter y:");
    scanf("%d",y);
    //         ^ address of int

在您编写的代码中,您读入了 int 指针,例如覆盖 int 的地址,然后取消引用它(另外),这会导致分段错误。

于 2012-08-06T04:31:05.403 回答
0

您可能需要更正一些错误。

** scanf 部分在这里制造了一些麻烦。他们应该像

scanf("%d",x);
scanf("%d",y);

** 你first_node应该连接到某事。我假设它是一个假头。所以在引入你的cur节点之后,你应该有first_node->next = cur

** 这个链表中的每个节点都没有连接到任何东西。你应该在你的主要功能中有这些:

while(inp_sum(&cur->x,&cur->y)<100){
    cur->next=malloc(sizeof(struct link_list));
    struct link_list *temp = cur;
    cur=cur->next;
    cur->next=0;
    cur->prev=temp;
}
于 2012-08-06T04:59:21.900 回答