ant2009
ant2009

Reputation: 22486

dereference a pointer to a pointer to a structure

gcc 4.7.2
c89

Hello,

I am trying to dereference a pointer to a pointer to a structure, and I get this error message when I do the following:

LOG_INFO("CHANNEL ID --- %d", *channel->id);

Compile error

request for member ‘id’ in something not a structure or union

If I try and cast it to the correct pointer type, I still get the same error message:

LOG_INFO("CHANNEL ID --- %d", (*(channel_t*)channel->id));

I solved the problem by declaring a new variable and assigning the address of where the structure is pointing to:

channel_t *ch = NULL;
ch = *channel;
LOG_INFO("CHANNEL ID --- %d", ch->id);

I am just wondering why the first two methods failed.

Many thanks for any suggestions,

structure:

typedef struct tag_channel channel_t;
struct tag_channel {
    size_t id;
    char *name;
};

The way I am calling it:

channel_t *channel = NULL;
channel = (channel_t*)apr_pcalloc(mem_pool, sizeof *channel);
LOG_CHECK(job_queue_pop(queue, &channel) == TRUE, "Failed to pop from the queue");

And the function, I am having trouble with:

apr_status_t job_queue_pop(apr_queue_t *queue, channel_t **channel)
{
    apr_status_t rv = 0;
    channel_t *ch = NULL;

    rv = apr_queue_pop(queue, (void**)channel);
    if(rv != APR_SUCCESS) {
        char err_buf[BUFFER_SIZE];
        LOG_ERR("Failed to pop from the queue %s", apr_strerror(rv, err_buf, BUFFER_SIZE));

        return FALSE;
    }

    ch = *channel;  
    LOG_INFO("CHANNEL ID --- %d", ch->id);
    LOG_INFO("CHANNEL NAME - %s", ch->name);

    return TRUE;
}

Upvotes: 4

Views: 4212

Answers (3)

CCoder
CCoder

Reputation: 2335

You have the operator precedence wrong. -> operator has a higher precedence than . operator. So -> is evaluated before . making it *(channel->id) which is wrong.

Look at the following code. It works fine.

typedef struct test_
{
   int i;
}test;

int main()
{
   test a;
   test *aptr = &a;
   test **aptrptr = &aptr;
   a.i=6;
   printf("\n%d\n",(*aptrptr)->i);
   return 0;
}

Read about precedence here.

Upvotes: 3

Heisenbug
Heisenbug

Reputation: 39164

It's an error due to operator precendece. Try this:

(*channel)->id

the operator "*" is evaluated after the operator "->".

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409166

You have the precedence wrong, it should be e.g.

(*channel)->id

Upvotes: 4

Related Questions