0

I have an assignment that requires to implement Singly Linked Lists in C and write a few functions. I'm bound to the way my lecture does it.. the struct and parameters of the function are determined so I can't change any of that.

The function is supposed to insert a list element with the value v at position pos into the list l.

I'll post what I was given first and my attempt after:

struct le {
    int value;
    struct le *next;
};

typedef struct le listelement;
typedef listelement *list;

int insert_pos(int v, int pos, list *l);

Again, I have to work with that the way it is. My attempt for the function is as follows:

int insert_pos(int v, int pos, list *l) {
    if (*l == NULL) {
        printf("empty");
        return -1;
    } else {
        listelement *new;
        new = malloc(sizeof(listelement));
        while (pos > 0) {
            l = l -> next;
            pos--;
        }
        new -> value = v;
        new -> next = *l;
        *l = new;
    }
}

The

l = l -> next;

causes problems in my compiler because it expects a pointer but changing it to *l doesn't do anything. The whole thing is probably a mess..

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Dennis
  • 57
  • 1
  • 2
  • 10
  • 4
    See also [Is it a good idea to typdef pointers](http://stackoverflow.com/questions/750178/is-it-a-good-idea-to-typedef-pointers) to which the short answer is "No". I realize you can't do anything about the interface; however, you should be cognizant that not everyone views your instructor's design as a good idea. One problem is that `l = l->next;` is wrong; you need `*l = (*l)->new;` to get it to compile — and you need to think about whether changing `*l` like that is a good idea (it probably isn't; you probably need to make a local copy). – Jonathan Leffler May 22 '17 at 17:04
  • I changed it to `l = &(*l)->next;` Which works.. I'll fix the loop next, thanks. – Dennis May 22 '17 at 17:31
  • Have you thought about if it should not be possible to insert a list element to the first position in an empty list? Or were you given instructions that inserting into an empty list should return an error, even when trying to insert to the first position? – SiggiSv May 22 '17 at 17:38
  • 1
    Retyping a previous (now deleted) comment: The dot `.` and arrow `->` operators bind very tightly and should be written without spaces around them: `l = l->next;`. Your loop is very trusting; you don't handle the case where someone says 'insert at position 20' but there are only 3 elements in the list. (The rewrite avoids giving the opposite advice from what I intended about the spacing around the dot and arrow operators.) – Jonathan Leffler May 22 '17 at 20:14

0 Answers0