C++ Pointer to pointer arrays

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!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
 
int* sort(int** newptr,  int n)
{
 
	for (int j{ 0 }; j < n; j++)
	{
		for (int i = 0; i < n; i++)
		{
 
			if (*(newptr[0]) > *(newptr[n - 1]))
			{
				int &temp1 = *newptr[0];
				*newptr[0] = *newptr[n - 1];
				*newptr[n - 1] = temp1;
			}
 
			if (*newptr[i] > * newptr[i + 1])
			{
				int &temp2 = *newptr[i];
				*newptr[i] = *newptr[i + 1];
				*newptr[i + 1] = temp2;
			}
		}
	}
 
	return *newptr;
}
int main()
{
	int arr[] = { 5,2,3,1,6,7 };
	int* ptr;
	ptr = arr;
	 int n = sizeof (arr) / sizeof (arr[0]);
	 int* sortedarr=sort(&ptr,n);
	 for (int i{ 0 }; i < n; i++)
	 {
		 std::cout << sortedarr[i] << std::endl;
	 }
	
	return 0;
}
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].
Last edited on
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.
One more thing:
1
2
3
int &temp = x; // temp is a reference, not a copy
x = y; // x is now a copy of y and temp == y
y = temp; // writes current value of x (y) to y 

The result of above is same as doing just:
x = y;
Topic archived. No new replies allowed.