Find the answer to your Linux question:
Results 1 to 2 of 2
okay.. i know this should be easier to understand, but the book i'm learning C from isn't clear on some things.. if a function returns a pointer to a linked ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Linux Engineer
    Join Date
    Sep 2003
    Location
    Knoxhell, TN
    Posts
    1,078

    [C] singly linked lists


    okay.. i know this should be easier to understand, but the book i'm learning C from isn't clear on some things..

    if a function returns a pointer to a linked list should it look like this:
    Code:
    int *blah(int *);
    or am i understanding this wrong? what i want to do is pass the head pointer (not hard.. the (int *) should do the trick), add links, and then return to the calling function.. to return the head pointer, i would just return a single pointer, correct?

    the book uses typedefs in the examples, so it makes it a little harder to read the code for a noob... which means it's harder to understand.
    Their code will be beautiful, even if their desks are buried in 3 feet of crap. - esr

  2. #2
    Linux Guru
    Join Date
    Oct 2001
    Location
    Täby, Sweden
    Posts
    7,578
    If you want a function to return an element of the list, you should make it return the type of the list. I'm not sure exactly where you may have gotten it wrong, so I'll give this entire example which shows some functions of a theme that I use frequently:
    Code:
    struct element
    {
        struct element *next, *prev;
        char *name;
        ...
    };
    
    struct element *list = NULL;
    
    struct element *newel(char *name)
    {
        struct element *new;
        
        new = malloc(sizeof(*new));
        new->name = name;
        new->prev = NULL;
        new->next = list;
        if(list != NULL)
            list->prev = new;
        list = new;
        return(new);
    }
    
    void freeelement(struct element *el)
    {
        if(el->prev != NULL)
            el->prev->next = el->next;
        if(el->next != NULL)
            el->next->prev = el->prev;
        if(el == list)
            list = el->next
        free(el);
    }
    
    struct element *findelement(char *name)
    {
        struct element *cur;
        
        for(cur = list; cur != NULL; cur = cur->next)
        {
            if(!strcmp(cur->name, name))
                break;
        }
        return(cur);
    }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •