使用交换函数交换二维数组指针中的地址 [英] Using a swap function to swap the address in pointers of a 2D-array

查看:48
本文介绍了使用交换函数交换二维数组指针中的地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于一个作业,我需要为 n 个向量数组制定一个排序算法.赋值特别告诉我不要交换指针指向的值,而是存储在这些指针中的地址.然后将使用这些指针打印结果.

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.

到目前为止我有这个:

交换功能

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

double* tmp;

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

还有我的主要功能

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("	Swapping..
");
            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("
");
}

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?

推荐答案

swap 函数可以看起来像

The swap function can look like

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

至于用于对数组进行排序的代码,它是无效的,没有意义.至少没有声明变量 argument1argument2.

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.

这篇关于使用交换函数交换二维数组指针中的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆