【问题标题】:access to data allocated by pointer in a structure issue访问结构问题中指针分配的数据
【发布时间】:2020-07-27 05:22:40
【问题描述】:

我正在编写使用结构和链接列表的代码。 请帮助我了解如何打印不在创建的列表头部的任何添加点。 任何尝试都是失败的。

*第二次打印调用的问题。

我唯一的选择是执行 head = head->next 以获得下一个变量吗? 结构:

typedef struct
{
    int x;
    int y;
}point;

typedef struct {
    point *p;
    struct Item *next;
}Item;

主要:

void main()
{   
    Item *head = (Item*)malloc(sizeof(Item)); //head of co-list
    if (!head) { //allocation check
        printf("Allocation failed (head)\n");
        exit(1);
    }
    head = addBegin(head);
    printf("head point: (%d,%d)\n",head->p->x,head->p->y);
    system("pause");
    head = addBegin(head);
    **printf("head second point: (%d,%d)\n",head->next->p->x,head->next->p->y);**
    system("pause");
    free(head->p);
    free(head);
}

功能:

Item * addBegin(Item *head)
{
    Item *tmp = (Item*)
        malloc(sizeof(Item));
    if (tmp) {
        tmp->p = (point*)malloc(sizeof(point));
        printf("Enter x's point: ");
        scanf(" %d", &tmp->p->x);
        printf("Enter y's point: ");
        scanf(" %d", &tmp->p->y);
        tmp->next = head;
        return tmp;
    }
    else{        //memory allocation failed
        printf("allocation failed (new head)\n");
        exit(2);
        return head;
}

【问题讨论】:

    标签: c pointers linked-list structure


    【解决方案1】:

    您可能想要遍历列表,代码类似于:

    for ( Item* current = &head;
          current != NULL;
          current = current->next ) {
      do_stuff_with(current->p);
    }
    

    当您到达列表末尾时停止:也就是说,当您处理完包含数据的最后一个节点时,其next 指针为NULL,并将current 更新为NULL

    顺便说一句,您想稍微调整Item 的定义,以:

    typedef struct Item {
        point *p;
        struct Item *next;
    } Item;
    

    包括 GCC 在内的一些编译器会意识到 Item.next 具有相同的类型,并停止向您提供有关匿名结构和不完整类型的虚假警告。

    您还需要决定是使用ItemPoint,还是使用itempoint。大小写不一致会造成混淆。

    【讨论】:

      猜你喜欢
      • 2013-03-02
      • 1970-01-01
      • 1970-01-01
      • 2012-05-05
      • 2011-08-11
      • 1970-01-01
      • 1970-01-01
      • 2021-03-14
      • 2021-12-16
      相关资源
      最近更新 更多