Search code examples
c++arrayspointersindexinglvalue

More LValue Errors


Below is a triple nested indexing scheme. My pointer to an array of pointers is dereferenced on the commented line... in theory this should give me a pointer. I subtract one from it and then reference it and reassign that to my pointer to the array of pointers. But that line gives an lvalue error for the operand "&".

Let me be perfectly clear. I want to both know why the error is occurring here AND get a method that works for assigning the address of the previous element in the array of pointers to my frame double pointer.

I will only accept full solutions that satisfy both criteria....

#include <iostream>

typedef struct frame_s {
  double ** TestArrayPointer;
} frame_t;

main () {

  double * TestArray;
  double ** TestPointerArray;
  TestArray = new double [100];

  TestPointerArray = new double * [100];

  for (unsigned int Counter = 0; Counter<100; Counter++)
  {
     TestArray[Counter]=Counter;
     TestPointerArray[Counter]=&(TestArray[Counter]);
  }

  frame_t Frames[10];
  for (unsigned int Counter = 0; Counter<10; Counter++)
    Frames[Counter].TestArrayPointer = &(TestPointerArray[Counter*10]);

  //Move pointer to point at array position one back.
  Frames[2].TestArrayPointer=
      &(*(Frames[2].TestArrayPointer)-1); //error! here <--

  //OUTPUT Values...
  for (unsigned int Counter = 0; Counter<100; Counter++)
    std::cout << "P: " << TestPointerArray[Counter] << " V: " 
          << *(TestPointerArray[Counter]) << std::endl;

}

Solution

  • Frames[2].TestArrayPointer=
      &(*(Frames[2].TestArrayPointer)-1);
    

    Here both the dereferencing and then taking back the address is unnecessary. You can directly do -

    Frames[2].TestArrayPointer = (Frames[2].TestArrayPointer)-1) ;
    

    But this has a potential problems.

    • What if the index is 0 ? Runtime error.
    • What if the index is the last index ? Memory leak.