Using a swap function to swap the address in point

2019-08-21 14:42发布

For an assignment I need to make a sorting algorithm for n amount of vector arrays. The assignment specifically tells me to not swap the value of what the pointers are pointing to, but the address that is stored in those pointers. The result will then be printed using those pointers.

My problem is that I can't seem to accomplish the swapping of the addresses that the pointers contain. I have searched SO for related questions but they almost all change the values of where the pointers are referring to.

So far I have this:

Swap function

void swap(double **p, double **q, int i, int j){

double* tmp;

tmp = &p;
*p= &q;
*q = tmp;
printf("\tSwapped [%d][%d] and [%d][%d]\n", i,j, (i-1), j);}

And my main function

int main (void){
int dim, num, *tmp;
int i, j, a;
double **w;
scanf("%d %d", &dim, &num);        /* read the dimension and amount of array*/                                                                  

w = calloc(num, sizeof(double *)); /* allocate array of num pointers */
for (i = 0; i<num; i++)
{
    /*allocate space for a dim-dimensional vector */
    w[i] = calloc(dim, sizeof(double));
    /* read the vector */
    for (j = 0; j < dim; j++)
    {
        scanf("%le", &w[i][j]);
    }
}

a = 0;
while (a <= num)
{
    /*sort num times*/
    i = (num -1);
    while(i != 0)
    {
        if ((argument1) > (argument2) )
        {   /*swap each columns of the rows individually*/
            printf("\tSwapping..\n");
            for(j = 0; j<dim; j++)
            {
                swap(&w[i][j], &w[i-1][j], i, j);
            }
        }
        i--;
    }
    a++;
}


for(i=0; i<num; i++)
{
    for(j=0; j<dim; j++)
    {
        printf("%e ",w[i][j]);
    }
    printf("\n");
}

return 0;

}

When i test this program, it does enter the swap function correctly but the printed result is the same as the input (so not swapped). Can anyone help me why this isn't working?

1条回答
ゆ 、 Hurt°
2楼-- · 2019-08-21 15:23

The swap function can look like

void swap( double **p, double **q )
{
    double *tmp = *p;
    *p = *q;
    *q = tmp;
}

As for the code that is used to sort arrays then it is invalid and does not make sense. At least the variables argument1 and argument2 are not declared.

查看更多
登录 后发表回答