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) {
 (...)
 }
 } 
}
asked Jan 31, 2014 at 12:29
2
  • 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. Commented Jan 31, 2014 at 12:39
  • Read Need of pointer to pointer Commented Jan 31, 2014 at 12:39

2 Answers 2

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).

answered Jan 31, 2014 at 12:33
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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.

answered Jan 31, 2014 at 12:37

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.