user2336315
user2336315

Reputation: 16067

How to initialize my pointer to NULL

Learning C, I'm trying to implement a little program. I have two structs like this:

typedef struct QueueNode_ QueueNode;
typedef struct TQueue_ TQueue;

struct QueueNode_ {
    QueueNode* next;
    const Task task;
};

struct TQueue_ {
    QueueNode* first;
    QueueNode* last;
};

Next I defined a method to initialize my queue:

void initializeQueue(TQueue* queue){
    queue = malloc(sizeof(TQueue)); //check if malloc returns NULL!
    queue->first = NULL;
    printf("%d", queue->first == NULL);
    queue->last = NULL;
}

And the main:

int main() {
    puts("TQueue example:");

    TQueue q;
    initializeQueue(&q);
    printf("%d", q.first == NULL);
}

I though that the above would print 11 but it prints 10 meaning that my pointer first is not set to null. I'm pretty sure that I miss something basic...

Why the above prints 10 and how to initialize properly the pointer of first to NULL in my initializeQueue method?

Thanks!

Upvotes: 0

Views: 133

Answers (2)

rodrigo
rodrigo

Reputation: 98348

The problem is that in C, arguments are always passed by value, unless explicitly passed as a pointer, so generally speaking you should not assign the arguments directly: it is confusing.

void initializeQueue(TQueue* queue) {
    queue = malloc(sizeof(TQueue)); //check if malloc returns NULL!

See? Upon entering the function, queue points to the queue from main, but then you allocate a new struct and make queue point to it. So the queue from main is never initialized!

The solution, remove the malloc:

void initializeQueue(TQueue* queue){
    queue->first = NULL;
    printf("%d", queue->first == NULL);
    queue->last = NULL;
}

Or if you prefer to go fully dynamic, to not take the queue as an argument but return a newly allocated one:

TQueue *initializeQueue(){
    TQueue* queue = malloc(sizeof(TQueue)); //check if malloc returns NULL!
    queue->first = NULL;
    printf("%d", queue->first == NULL);
    queue->last = NULL;
    return queue;
}

And modify the main function accordingly.

Upvotes: 5

Some programmer dude
Some programmer dude

Reputation: 409166

This line is the fault:

queue = malloc(sizeof(TQueue)); //check if malloc returns NULL!

You have already allocated memory for the structure in the main function, so you don't need to do it again.

In fact, what the line is doing is allocating memory, assigning it to the pointer (and remember that arguments are passed by value so it overwrites the local copy) and you change only that structure in the function, not the one passed in by the call.

Upvotes: 3

Related Questions