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 getInstead, just make your loop