简体   繁体   中英

Error in initialization of a pointer to structure

I have this program that I'm trying to modify it, but I don't understand why the statement: struct Link * temp = cap; doesn't print me the number that I assigned to the linked list. Thanks in advance!

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

You need to pass the Link * by reference to change it, that's a 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;
}

and in your main(...) use

Insert(&cap, n);

or you could return the new Link * from your Insert(...) like this;

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

and in your main(...) use

cap = Insert(cap, n);

This line does not do anything, because cap inside Insert is a copy of cap from the main :

cap = temp;

The change gets discarded as soon as Insert exits, so main 's cap remains NULL .

Change Insert 's signature to return Link* , and assign it to cap in the call from 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;
}

The call looks like this:

cap = Insert(cap, n);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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