honeyPot honeyPot - 2 months ago 7
C Question

Sort the pointers by the value they are pointing to in C

I want to sort pointers that point to an array in C, but without moving index positions. Here is a picture of what I am trying to do:
enter image description here

enter image description here

Here is the code, but it doesn

t work, and I don
t know what the problem is.

#include <stdio.h>
#include <stdlib.h>

int main()
{

int niz[7] = { 4, 2, 5, 7, 6, 1, 3};


int j,i;
int *temp;

int *nizptr = niz;
int **niz2ptr = &nizptr;

for(i = 0; i < 7; i++)
{
for(j = 0; j < 7; j++)
{
if( niz[i] < niz[j] )
{
temp = *(niz2ptr + i);
*(niz2ptr+i) = *(niz2ptr + j);
*(niz2ptr+j) = temp;
}
}
}


for(i = 0; i < 7; i++)
{
printf("%d",*(*(niz2ptr + i)));
}
return 0;
}

Answer

The image you've shown is not correct. After the initializations:

int *nizptr = niz;
int **niz2ptr = &nizptr;

the state looks like this:

enter image description here

The pointer niz2ptr is not pointing to an array, but to a pointer. Thus the indexing you make here:

temp = *(niz2ptr + i);

which is identical to:

temp = niz2ptr[i];

will read out of bounds of when i is greater than one. This happens because it tries to read at the address &nizptr+i instead of niz+i.

To fix the code, the type of variable temp must be changed to int, not a pointer to int.

Since nizptr is pointing to an array, you can index it:

temp = nizptr[i];

To achieve the same with niz2ptr, first dereference it to get the value of nizptr, and the index it:

temp = (*niz2ptr)[i];

This should be done whenever niz2ptr is used.

Comments