Hi guyz, So I am learning about the use of pointers to pointers, and I have implemented a program below on the sorting of arrays. But I kept receiving an error that breaks at the first point of the if statement. Is anyone able to help me on this? Appreciate it!
First, I just want to say that there's no point is passing your arr as a double-pointer to a sort function. It's never used in such a way to warrant 2x indirection.
In short, you're going out of bounds of your array.
In main, ptr points to the first address of arr, OK.
But then you pass &ptr into the function.
&ptr is a totally different location in memory than ptr.
So doing (&ptr + i) and dereferencing that is getting a totally different location in memory than your original array.
Again, there's no point in passing a double-pointer here, but if you must, then at the beginning of your function, do int* actual_ptr = *newptr;
Then use actual_ptr[i].
Every time you wrote *newptr[whatever] you should have written (*newptr)[whatever]. newptr is a pointer to a single pointer to an array, but *newptr[i] accesses as if newptr was a pointer to an array of single pointers.
The if on line 11 is also incorrect for the same reason. It should be (*newptr)[0] > (*newptr)[n - 1]. Although I suspect that if block shouldn't be there at all.
I would advice against writing code with multiple levels of indirection. The code becomes too confusing and thus error-prone. In this particular case the function could have been rewritten so that newptr was of type int *, so the extra level of indirection is entirely pointless.
One more thing: Even after you fix the indirection issues, the if statement on line 18 can go out of bounds when dereferencing array[i+1] because array[i] might already be the last element.