与指针奇怪的问题,同时实施链表 [英] Odd problem with pointer while implementing a linked list

查看:78
本文介绍了与指针奇怪的问题,同时实施链表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用C实现一个链表,和我想的头节点存储在一个单独的结构。然而,这似乎是头节点被莫名其妙地重新分配每当我添加一个节点。

 的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;结构BC_node {
    结构BC_node *接下来的;
    void *的数据;
};
结构BC_list {
    结构BC_node *头;
    结构BC_node *尾;
};空虚
BC_list_push(结构BC_list *名单,无效*数据)
{
    结构BC_node *节点=释放calloc(1,sizeof的(结构BC_node));    如果(列表 - >!头= NULL)
        的printf(头数:%d \\ n,*((INT *)(列表 - >头) - GT;数据));    于节点>接着= NULL;
    与于节点GT;数据=数据;
    如果(列表 - >头== NULL){
        的printf(头为空\\ n);
        列表 - >头=节点;
    }
    如果(列表 - >!尾= NULL){
        (列表 - >尾) - >接下来=节点;
    }
    列表 - >尾=节点;    的printf(头数:%d \\ n,*((INT *)(列表 - >头) - GT;数据));
}INT
主要(无效)
{
    INT I;
    结构BC_list *名单=释放calloc(1,sizeof的(结构BC_list));    列表 - >头= NULL;
    列表 - >尾= NULL;
    对于(I = 0; I&下; 3;我+ +)
        BC_list_push(列表,和放大器;我);
    返回0;
}

输出:

 头为空。
头:0
头:1
头:1
头:2
头:2


解决方案

数据成员只是一个指针变量 I ,所以当你打印 * 的数据,你刚才看到的那轮在计数器的值的循环。你所有的节点都具有的相同的数据值!

I'm trying to implement a linked list in C, and I want to store the head node in a separate struct. However, it seems like the head node is being reassigned somehow whenever I add another node.

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

struct BC_node {
    struct BC_node *next;
    void *data;
};
struct BC_list {
    struct BC_node *head;
    struct BC_node *tail;
};

void
BC_list_push(struct BC_list *list, void *data)
{
    struct BC_node *node = calloc(1, sizeof(struct BC_node));

    if (list->head != NULL)
        printf("head: %d\n", *((int *) (list->head)->data));

    node->next = NULL;
    node->data = data;
    if (list->head == NULL) {
        printf("head is null.\n");
        list->head = node;
    }
    if (list->tail != NULL) {
        (list->tail)->next = node;
    }
    list->tail = node;

    printf("head: %d\n", *((int *) (list->head)->data));
}

int
main(void)
{
    int i;
    struct BC_list *list = calloc(1, sizeof(struct BC_list));

    list->head = NULL;
    list->tail = NULL;
    for (i = 0; i < 3; i++)
        BC_list_push(list, &i);
    return 0;
}

The output:

head is null.
head: 0
head: 1
head: 1
head: 2
head: 2

解决方案

Your data member is just a pointer to the variable i in main, so when you print *data you just see the value of the counter during that round of the loop. All your nodes have the same data value!

这篇关于与指针奇怪的问题,同时实施链表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆