繁体   English   中英

初始化结构指针时出错

[英]Error in initialization of a pointer to structure

我有这个程序,我正在尝试修改它,但我不明白为什么声明: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;
}

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

这条线没有做任何事情,因为capInsert是副本capmain

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM