初始化结构指针时出错

时间:2018-02-06 21:08:53

标签: c struct linked-list

我有这个程序,我正在尝试修改它,但我不明白为什么声明: struct Link * temp = cap; 不打印我分配给链表的号码。 提前谢谢!

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;
}

2 个答案:

答案 0 :(得分:2)

您需要通过引用传递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);

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

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);

答案 1 :(得分:1)

此行没有执行任何操作,因为cap中的Insert是来自cap的{​​{1}}的副本:

main

一旦cap = temp; 退出,更改就会被废弃,因此Insert main仍为cap

更改NULL的签名以返回Insert,并在Link*的来电中将其分配给cap

main

电话看起来像这样:

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;
}