3

I'm new to C and new to programming as well and I've just started looking at linked lists.

static struct post {
    char * str;
    struct post * next;
}
head = {0, NULL};


int stringdb_add(const char * str) {
    int pos = 0;
    struct post * new_input = (struct post * ) malloc(sizeof(struct post));
    new_input - > str = (char * ) malloc(strlen(str) + 1);

    if (head.next == NULL) {
        strcpy(new_input - > str, str);
        new_input - > next = NULL;
        head.next = new_input;
    } else {
        while (head.next - > next) {
            ++pos;
            head.next = head.next - > next;
        }
        strcpy(new_input - > str, str);
        new_input - > next = NULL;
        head.next - > next = new_input;
    }

    return pos;
}

The function "stringdb_add" is supposed to return the position the new node has been placed in, but when I test the function I only get (00111111....).

This is probably because the list never links properly.

1
  • You get a +1 for trying .. But might get a -1 for indentation - sort it Commented Jan 25, 2014 at 9:39

1 Answer 1

3
while (head.next->next) {
   ++pos;
   head.next = head.next->next;        
}

You are permanently changing head.next which is surely not what you want. You probably want something like:

struct post *p = &head;
while (p->next->next)
/* ... */

Nitpick: strcpy(new_input->str, str) can be in a single place, before the if.

Sign up to request clarification or add additional context in comments.

1 Comment

Okay, i totaly got it working now, the whole p pointer made everything easier. thanks for your help and a really qucik answer! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.