【问题标题】:Error in initialization of a pointer to structure结构指针初始化错误
【发布时间】:2018-02-06 21:08:52
【问题描述】:

我有这个程序,我正在尝试修改它,但我不明白为什么会有这样的声明: 结构链接 * 温度 = 上限; 不会打印我分配给链接列表的数字。 提前致谢!

struct Link
{
    int data;
    struct Link *urmatorul;
};

void Insert(Link * cap, int n)
{
    struct Link * temp = (Link*)malloc(sizeof(struct Link));
    temp->data = n;
    temp->urmatorul = NULL;
    if(cap != NULL)
        temp->urmatorul = cap;
    cap = temp;
}

void Print(Link * cap)
{
    struct Link *temp = cap;
    printf(" %d", cap->data);
    printf("The number is: ");
    while(temp != NULL)
    {
        printf(" %d", temp->data);
        temp = temp->urmatorul;
    }
    printf("\n");
}

int main()
{
    struct Link * cap;
    cap = NULL;
    printf("How many numbers? \n");
    int x, n, i;
    scanf(" %d", &x);
    for(i = 0; i < x; ++i)
    {
        printf("Enter the number: \n");
        scanf("%d", &n);
        Insert(cap, n);
        Print(cap);
    }
    return 0;
}

【问题讨论】:

  • C 按值传递参数。您的capNULL,在Insert() 之后从未更改。
  • 回想一下你的课本或课堂笔记。他们对将参数传递给函数有什么看法?你还记得任何关于它的按价值吗?这意味着它们是复制的,无论您在函数内部对副本进行多少修改,原始的都不会改变?做一些关于在C中模拟通过引用传递的研究。
  • Insert 需要返回你的链表的新根节点。您的插入函数正在泄漏内存。

标签: c struct linked-list


【解决方案1】:

您需要通过引用传递Link * 来更改它,即Link **

void Insert(Link **cap, int n)
{
    struct Link * temp = (Link*)malloc(sizeof(struct Link));
    temp->data = n;
    temp->urmatorul = NULL;
    if(*cap != NULL)
        temp->urmatorul = *cap;
    *cap = temp;
}

并在您的main(...) 中使用

Insert(&cap, n);

或者您可以像这样从您的Insert(...) 返回新的Link *

Link * Insert(Link * cap, int n)
{
    struct Link * temp = (Link*)malloc(sizeof(struct Link));
    temp->data = n;
    temp->urmatorul = NULL;
    if(cap != NULL)
        temp->urmatorul = cap;
    return temp;
}

并在您的main(...) 中使用

cap = Insert(cap, n);

【讨论】:

  • return cap = temp; 是一个毫无意义的任务。当然,即使是弱优化器也会删除它,但它在语义上是不正确的。只需返回温度。
【解决方案2】:

这行不做任何事情,因为Insert 中的capcap 的副本,来自main

cap = temp;

一旦Insert 退出,更改就会被丢弃,所以maincap 仍然是NULL

Insert的签名更改为返回Link*,并在来自main的调用中将其分配给cap

Link* Insert(Link * cap, int n)
{
    struct Link * temp = malloc(sizeof(struct Link)); // No need to cast
    temp->data = n;
    temp->urmatorul = cap; // No need for the conditional
    return temp;
}

调用如下所示:

cap = Insert(cap, n);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多