Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

declaration in local vs global

#include<stdio.h>
#include<stdlib.h>

struct node
{
    int data;
    struct node* link;
};

void insert_last(struct node **head, int value)
{
    struct node* new = malloc(sizeof(struct node));
    new->data = value;

    if( !*head )
    {
        new->link = NULL;
        *head = new;
    }
    else
    {
        struct node* last = *head;
        while(last->link)
        {
            last = last->link;
        }
        new->link = NULL;
        last->link = new;
    }
}

    struct node *head;

int main()
{
    insert_last( & head,  5);
    insert_last( & head, 10);
    insert_last( & head, 15);
    printf("%d  ", head->data);
    printf("%d  ", head->link->data);
    printf("%d  ", head->link->link->data);

}

If I Declare struct node *head inside of the main the programm is not working.
what is the reason ?
> if i declare globally its working, otherwise not working.
> I repeating question because stackoverflow asking add more details(> If I Declare struct node *head in side of the main the programm is not working.
what is the reason ?
> if i declare globally its working, otherwise not working.)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

There is a initialization bug: In insert_last(), the variable head is tested without having been initialized explicitely. If head is declared as global, it is located in a global section that is most probably initialized to 0 by the loader (when the program is started); if head is declared in the function main() then it is located in the stack of the function and is not set to 0.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading