簡體   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