Thread: Can somebody explain in parts what this code does?

  1. #1
    Registered User
    Join Date
    Nov 2018
    Posts
    9

    Can somebody explain in parts what this code does?

    I am busy with learning C and could somebody explain in parts what this code does?


    Code:
    //I am intrested in the mean of this (which is in a methode)
    struct node *link =(struct node*) malloc(sizeof(struct node));
    
    
    //Where the struct looks like
    struct node {
       int data;
       int key;
        
       struct node *next;
       struct node *prev;
    };

  2. #2
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,111
    Quote Originally Posted by jenniferruurs View Post
    I am busy with learning C and could somebody explain in parts what this code does?


    Code:
    //I am intrested in the mean of this (which is in a methode)
    struct node *link =(struct node*) malloc(sizeof(struct node));
    
    
    //Where the struct looks like
    struct node {
       int data;
       int key;
        
       struct node *next;
       struct node *prev;
    };
    I would split this line into two lines:
    Code:
    struct node *link = NULL;
    link = malloc(sizeof(struct node);
    if(link == NULL)
    {
        // Error handling code goes here if the allocation failed
    }


    "link" is a pointer to a struck node. malloc() allocates enough space on the heap to hold one struct node data. If malloc() was successful, the next step would be to initialize the members of the struct to 0, NULL, or some legitimate data, or use memset() to zero out the struct allocated. calloc() would also do the same thing.

    You should always test the return value from malloc(), calloc() or realloc(). They will return NULL if they fail to allocate or expand the memory area.

    A good book on the C Programming Language would explain this, and other concepts.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. i cant measure elapsed time between parts of code
    By wesdom in forum C++ Programming
    Replies: 29
    Last Post: 10-23-2014, 02:44 AM
  2. Question related to returning to earlier parts of the code.
    By Cgrasshopper in forum C Programming
    Replies: 2
    Last Post: 03-13-2010, 11:00 PM
  3. Explain this c language code....only 2 parts of it?
    By ankit8946 in forum C Programming
    Replies: 22
    Last Post: 10-31-2009, 03:33 PM
  4. C source code to split any given file into many parts
    By m.sudhakar in forum C Programming
    Replies: 2
    Last Post: 08-15-2006, 03:43 AM
  5. Completely seperating parts of code
    By Boksha in forum C++ Programming
    Replies: 3
    Last Post: 08-14-2005, 11:36 AM

Tags for this Thread