This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Problem setting pointer via function

I have a problem when I try to get a function to update a the address of a pointer.
Code:

const unsigned char array1[10] = {1, 2, 3, 4....}

void func1 (const unsigned char *ptr)
{
  ptr = array1;
}

void func2 (void)
{
  const unsigned char *ptr1;

  func1 (ptr1);

  if (ptr1[0] == 1)
  {
    .....
  }
}

The problem is, the ptr in func1 gets the right address, but when I return to func2, ptr1 doesn't get updated. I have tried to remove the const from the variable definition in func2 without any succes.

array1 must be defined as a const because in the real code it's a lot bigger.

I have tried to set ptr1 directly in func2.

...

void func 2 (void)
{
  const unsigned char *ptr1;

  ptr1 = array1;

  if (ptr1[0] == 1)
  {
    .....
  }
}

This work fine. But this is not an option in my application.

uC: STR712
compiler: CARM

Parents
  • Try this:

    void func1 (const unsigned char **ptr)
    {
      *ptr = array1;
    }
    
    void func2 (void)
    {
      const unsigned char *ptr1;
    
      func1 (&ptr1);
    
      if (ptr1[0] == 1)
      {
        .....
      }
    }
    

    Actually this is textbook C stuff. You might want to consult your favorite C book once more.

    - mike

Reply
  • Try this:

    void func1 (const unsigned char **ptr)
    {
      *ptr = array1;
    }
    
    void func2 (void)
    {
      const unsigned char *ptr1;
    
      func1 (&ptr1);
    
      if (ptr1[0] == 1)
      {
        .....
      }
    }
    

    Actually this is textbook C stuff. You might want to consult your favorite C book once more.

    - mike

Children