【问题标题】:c - segmentation fault storing input to and adding two pointersc - 存储输入并添加两个指针的分段错误
【发布时间】:2012-08-06 04:25:22
【问题描述】:

执行此操作时出现分段错误,但编译器没有显示任何错误。 如果我问的是非常基本的问题,请原谅我,因为我长期以来一直不擅长用 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(节点的成员)的指针发送到返回它们的函数的函数在接受输入并将输入存储到它们之后求和。

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

问候

【问题讨论】:

    标签: c pointers segmentation-fault


    【解决方案1】:

    xy 已经是指针,所以:

        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 的地址,然后取消引用它(另外),这会导致分段错误。

    【讨论】:

    • 解决了分割问题,但现在我无法添加指针,invalid operands to binary + (have ‘int *’ and ‘int *’ 出现错误,请您帮我解决一下。
    • 从您的评论中,我假设您尝试执行 z=x+y; 来添加指针,这是无效的,您仍然应该取消引用它们:z=*x+*y;
    • 我先这样做了,然后我得到了这个输出Enter x:2 Enter y:3 37281808+37281812Enter x:
    • 然后我想我可能会添加地址或类似的东西,所以我删除了*
    • 对不起!!它有效,我正在打印地址而不是添加地址!谢谢:)
    【解决方案2】:

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

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

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

    ** 你的first_node 应该连接到某个东西。我假设它是一个假头。所以在引入你的cur 节点之后,你应该有first_node-&gt;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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-18
      • 2016-02-24
      • 1970-01-01
      • 1970-01-01
      • 2012-04-10
      • 2021-05-25
      • 2023-04-04
      相关资源
      最近更新 更多