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) {
(...)
}
}
}
2 Answers 2
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).
1 Comment
**pcan.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.
T *pcanyou cannot change value ofpcanitself, because it's passed by value, but you can change value of what it's pointing too, meaning value of*pcan.