views:

239

answers:

2

I have set up the following struct:

typedef struct _thread_node_t {
    pthread_t thread;
    struct thread_node_t *next;
} thread_node_t;

... and then I have defined:

// create thread to for incoming connection
thread_node_t *thread_node = (thread_node_t*) malloc(sizeof(thread_node_t));
pthread_create(&(thread_node->thread), NULL, client_thread, &csFD);

thread_node->next = thread_arr; // assignment from incompatible pointer type

thread_arr = thread_node;

where thread_arr is thread_node_t *thread_arr = NULL;

I don't understand why the compiler is complaining. Maybe I'm misunderstanding something.

+4  A: 

It's because thread_arr is a thread_node_t pointer, and your next member is a struct thread_node_t pointer. Not the same thing.

Macmade
What I'm trying to work out, is what *is* a `struct thread_node_t`? Why does the questioner's typedef compile?
Steve Jessop
Oh, I get it, it's a forward declaration of an incomplete type.
Steve Jessop
+1  A: 

Shouldn't struct thread_node_t *next; be struct _thread_node_t *next;


Also, do away with the explicit cast.

thread_node_t *thread_node = (thread_node_t*) malloc(sizeof(thread_node_t));

to

thread_node_t *thread_node = malloc(sizeof(thread_node_t));
N 1.1
OMG! Yeah... thanks. I can't believe I missed that. I had a struct like this working in a previous program and I was killing myself because I couldn't figure it out. Thanks a bunch.
Hristo
@Hristo: n0 problem! :)
N 1.1
About the explicit cast: No need for ANSI C, but required for C++.
Macmade
Or for that matter, `thread_node_t *thread_node = malloc(sizeof *thread_node);`.
Steve Jessop
@Macmade: tagged C.
N 1.1
@Macmade: I'm not wholly decided whether to cast the result of `malloc` or not, but one of the things that swings it is that as you say, if you leave out the cast it won't compile as C++. I consider this a good reason to leave out the cast!
Steve Jessop