Bogdan Ruzhitskiy
Bogdan Ruzhitskiy

Reputation: 1237

One linked list for python using C api

I'm trying to make one linked list for Python using C api. This stuff works:

typedef struct list {
    int item;
    struct list *next;
} list;

void insert(list **self, int item) {
    list *p = malloc(sizeof(list));
    p->item = item;
    p->next = *self;
    *self = p;
}

int main() {
    list *myList = NULL;
    insert(&myList, 1);
    return 0;
}

but Python C api use *self, instead **self. So, how can it works, if insert function would be like this:

void insert(list *self, int item) {

Upvotes: 1

Views: 102

Answers (1)

Erik Nyquist
Erik Nyquist

Reputation: 1317

Well, you can just drop the *, i.e.:

void insert(list *self, int item) {
    list *p = malloc(sizeof(list));
    p->item = item;
    p->next = self;
    self = p;
}

But I don't think this will behave like you expect, because the line self = p will not actually modify the same pointer that the caller was using. Your function gets a seperate copy of *self when it runs (C is pass-by-value). If you want to modify something in a function and have the caller see the change, the normal approach is to use a pointer-- so you don't need to modify the copy of the pointer passed into the function, but you can use it to access the same piece of memory that the caller has been working with. In your case, the caller is working with a pointer to myList, so if you want the function to change the value of that pointer, you need a pointer to a pointer i.e. list **self.

Upvotes: 1

Related Questions