This function reverses the array of pointers and returns it to the main. The main problem is that the code returns an Exception thrown: read access violation. fptr was 0xCCCCCCCC.
What could be the source of error?
int* mirror(int* p[], int n) {
int* ptr,* fptr;
int swap;
ptr = p[0];
fptr = p[n-1];
while (fptr > ptr) {
swap = *ptr;
*ptr = *fptr;
*fptr = swap;
ptr++;
fptr--;
}
return *p;
}
This is the problem:
while (fptr > ptr) { ... }
ptr
is the first elements (the first pointer), and fptr
is the last element (the last pointer), and you are going through the array while the first element is less than the last element, but this imply that the elements in the array are inserted in order of address, which i believe is not..
Instead you should use the dimension (n
) in order to do that:
int** mirror(int* p[], int n) { // return a pointer to integers pointer, not a pointer to integer
for(int i = 0; i < n/2 ; i++){ // go through the first half of the array
int* tmp = p[i]; // and those three lines swap the current and the n - current elements
p[i] = p[n-i-1];
p[n] = tmp;
}
return p;
}