Dereferencing member pointer

222 views Asked by At

I have a c++ struct which has a dynamically allocated array as a pointer. I have a function to reverse the array, but it doesn't seem to work (I think its because the temporary variable points to the original value).

struct s {

   int *array;
   int length;

   ...

   s(int n) {
       this->array = new int[n];
       this->length = n;
   }

   ...

   void reverse() {

       for (int i = 0; i < this->length; i++) {
           int n = this->array[i];
           this->array[i] = this->array[this->length - i - 1];
           this->array[this->length - i - 1] = n;
       }

   }

   ...

}

I think what this is doing is this->array[this->length - i - 1] = this->array[i] Hence the array remains the same and doesn't get reversed. I don't know how to deference the array pointer or how to just take the value of this->array[i] in n.

2

There are 2 answers

0
Iluvatar On

The reason your reverse doesn't work is that you're going through the length of the whole array. You need to only go through half of it. If you go through the second half, then you're un-reversing it.

As an example, if you try to reverse [1, 2, 3, 4] you get

after i = 0: [4, 2, 3, 1]
after i = 1: [4, 3, 2, 1]
--- reversed ---
after i = 2: [4, 2, 3, 1]
after i = 3: [1, 2, 3, 4]
--- back to original ---

Instead, just make your loop

for (int i = 0; i < this->length / 2; i++) {
    ...
}
0
tinstaafl On

On a side note, using 2 indexers will simplify your code considerably:

void reverse()
{
    int limit = length / 2;
    for ( int front = 0 , back = length - 1; front < limit; front++ , back-- )
    {
        int n = array[front];
        array[front] = array[back];
        array[back] = n;
    }

}