简体   繁体   中英

Dereferencing member pointer

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.

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++) {
    ...
}

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;
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM