Using a swap function to swap the address in pointers of a 2D-array

╄→гoц情女王★ 提交于 2019-12-13 04:19:01

问题


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:


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.



来源:https://stackoverflow.com/questions/49476057/using-a-swap-function-to-swap-the-address-in-pointers-of-a-2d-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!