1

I'm new to C. I'm trying to pass a struct list to a function and within that function fill the list. Code is as follows:

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

struct Abc {
    int test;
    struct Abc *next;
};

void demo_fill(struct Abc *data);

int main(int argc, char **argv) {
    struct Abc *db = NULL;
    demo_fill(db);
    printf("%d\n",db->test);
    return 0;
}

void demo_fill(struct Abc *data) {
    int i;
    for( i = 0; i < 5; i++ ) {
       struct Abc *new;
       new = malloc(sizeof(struct Abc));
       new->test = i;
       new->next = data;
       data = new;
   }  
}

When running this a 'Segmentation fault (core dumped)' error occurs because the struct is still NULL when I try to print the first element. What am I doing wrong?

1
  • 1
    You're not running in a debugger before posting to SO, is what you are doing wrong. Commented Feb 14, 2013 at 16:51

3 Answers 3

5

You're passing the pointer by value. You need to pass a pointer to a pointer if you want the change the value of the caller's pointer:

int main(int argc, char **argv) {
    struct Abc *db = NULL;
    demo_fill(&db);
    printf("%d\n",db->test);
    return 0;
}

void demo_fill(struct Abc **data) {
    int i;
    for( i = 0; i < 5; i++ ) {
       struct Abc *new;
       new = malloc(sizeof(struct Abc));
       new->test = i;
       new->next = *data;
       *data = new;
   }  
}
Sign up to request clarification or add additional context in comments.

Comments

2

Assigning data to new will have no effect. data is a local copy of the pointer. Pass a double pointer to fix that. Something like this:

void demo_fill(struct Abc** data) {
    int i;
    for( i = 0; i < 5; i++ ) {
       struct Abc *new;
       new = malloc(sizeof(struct Abc));
       new->test = i;
       new->next = *data;
       *data = new;
   }  
}

And of course you will have to pas the pointer to db in main:

demo_fill(&db)

2 Comments

Thanks, that works. But still I get a warning from the compiler: test.c:24:15: warning: assignment from incompatible pointer type [enabled by default] - That's 'new->next = data;' within the loop
Thanks man. You solved my problem. Marking as answered in 9 mins.
1

You can pass a pointer to the pointer as the other two answers say, so i just point out an alternative you might also consider: Instead of using a single struct you could use one struct for the list and another for entry-links:

struct link {
    int test;
    struct link* next;
};
struct list {
    struct link* first;
};

void demo_fill(struct list* data);

You can then modify the first entry of the list without thinking about ** syntax.

Comments

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.