0

What do I misunderstand about processing pointers ?
I have CAN1_msg_t buffer with in/out pointers
I want to set pCAN1RxMsg pointer to eq. c1rxbuf->buf[0] in my CAN1GetPtr() function.

struct CAN1_msg_t {
    uint8_t flags;
    uint32_t id;
    uint8_t data[8];
};

struct can1_buf_st
{
    unsigned int in;    // In Index
    unsigned int out;   // Out Index
    struct CAN1_msg_t buf[100];   // Buffer
};

int CAN1GetPtr(struct CAN1_msg_t *pcan)
{
    struct  can1_buf_st *p = &c1rxbuf;

    pcan =  &(p->buf[p->out++]);

    return 1;
}

static struct can1_buf_st c1rxbuf = { 0, 0, };    

void main()
{
    struct CAN1_msg_t  *pCAN1RxMsg;

    if(CAN1GetPtr(pCAN1RxMsg)) {

        if((*pCAN1RxMsg).id == 0x100) {
            (...)
        }
    }   
}
maria87
  • 15
  • 3
  • As you are passing `T *pcan` you cannot change value of `pcan` itself, because it's passed by value, but you can change value of what it's pointing too, meaning value of `*pcan`. – zoska Jan 31 '14 at 12:39
  • Read [Need of pointer to pointer](http://stackoverflow.com/questions/18306935/need-of-pointer-to-pointer/18307020#18307020) – Grijesh Chauhan Jan 31 '14 at 12:39

2 Answers2

1

Change:

int CAN1GetPtr(struct CAN1_msg_t *pcan)
{
    struct  can1_buf_st *p = &c1rxbuf;

    pcan =  &(p->buf[p->out++]);

    return 1;
}

To:

int CAN1GetPtr(struct CAN1_msg_t **pcan)
{
    if (c1rxbuf.out < sizeof(c1rxbuf.buf)/sizeof(*c1rxbuf.buf))
    {
        *pcan =  &c1rxbuf.buf[c1rxbuf.out++];
        return 1;
    }
    return 0;
}

And in function main, change CAN1GetPtr(pCAN1RxMsg) to CAN1GetPtr(&pCAN1RxMsg).

barak manos
  • 29,648
  • 10
  • 62
  • 114
  • Yes - you want to change the VALUE of the pointer, so you need to pass the ADDRESS of the pointer, i.e. the place where the new value must be stored - thus `**pcan`. – Floris Jan 31 '14 at 12:34
1

You're passing a pointer to a struct to the function. This means you are passing the address to that struct to the function, doing so, will copy the address into the stack segment and gives it as the input argument to the function.

In the function, you will have the address to the content of the struct, which you might be able to change, but the address itself is a copy of the address you had in you main function.

If you want to change the address itself, you need to pass the address to the address value, which is pointer to pointer, or as pointed out, struct CAN1_msg_t **pcan. Then you can access the address value, and from there if you wish, you can follow the address once more and access the value itself.

adrin
  • 4,511
  • 3
  • 34
  • 50