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

  • 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

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

    You need to review how 'C' passes parameters to functions - it passes by value only...

  • The problem is, the ptr in func1 gets the right address, but when I return to func2, ptr1 doesn't get updated.

    That's because func1 only gets a copy of the value of ptrl. It cannot modify ptrl with this.

    Essentially, func1 in its present form does not do anything.

  • "update the address of a pointer."

    That might be just a typo, or a problem with English, or it might illustrate a fundamental misunderstanding:

    You cannot update the address of a pointer.

    A pointer is a variable like any other - it occupies a certain location in memory, that location is called its address, and it is fixed at build-time by the tools (or possibly at load-time by the loader, if you have such a thing).

    The value of a pointer is also an address - it is the address of the pointed-to thing (the "target" of the pointer).

    Again, check your 'C' textbook on this!

  • That solved the problem..... Thanks

    I did mean change the address the pointer is pointing to not "update the address of a pointer." ;-)

    Thats the problem when my text book i missing.... :-(