noa feldman
noa feldman

Reputation: 11

can't change pointer fields in struct

This is kind of my first time using struct, so I apologize if it's too basic... I have a struct which keeps a pointer as a field:

struct List;
typedef struct List* ListRef;

struct List{
    void *data;
    ListRef next;
    ListRef last;
};

I try to create a new pointer to the struct, this is the function I wrote:

ListRef newList(void* headData){
    struct List *list= malloc(sizeof(struct List));
    if (list == NULL){
            return NULL;
    }

    list->data = headData; // I checked here and list-> !=NULL
    list->next = NULL;
    list->last = list;
    return list;
}

The problem is that after the function returns the ListRef, the field 'data' is NULL (I checked and inside the function it's not NULL). I also added a test field which is not a pointer, and this one remained the same after the function returned the ListRef. This made me believe it has something to do with me returning a pointer within a pointer, but I don't really understand what I'm doing wrong. Also, the field 'last' is not NULL - maybe it's because 'data' is void? I really am kind of lost...

Upvotes: 0

Views: 220

Answers (1)

Maged Elghareib
Maged Elghareib

Reputation: 119

The field data should be NULL only if you pass NULL to the call of newList().

You say

(I checked and inside the function it's not NULL)

If you mean checking with a debugger before the execution of list->data = headData; line, it most probably will not be NULL, as it is not initialized yet. After the execution of the line, it should be whatever address headData contains (which is the function argument).

For the last point, the field last could not be NULL. It points to the object itself (as if it mimics C++'s this pointer). As last is assigned after if (list == NULL) check passes, it is certainly not equal to NULL. (As Paul Griffiths indicates in his comment.)

Upvotes: 1

Related Questions