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.