c - 使用交换函数交换二维数组指针中的地址

标签 c arrays pointers 2d swap

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

我的问题是我似乎无法完成指针包含的地址的交换。我已经搜索了相关问题,但它们几乎都改变了指针所指位置的值。

到目前为止我有这个:

交换功能

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);}

以及我的主要功能

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;

}

当我测试这个程序时,它确实正确地进入了交换函数,但打印的结果与输入相同(因此没有交换)。谁能帮我解释为什么这不起作用?

最佳答案

交换函数看起来像

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

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

关于c - 使用交换函数交换二维数组指针中的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49476057/

相关文章:

objective-c - 数组内数组项替换

c++ - 带 double 的紧凑指针表示法

c - 将结构的指针成员分配给 null

c - 如何用另一个文件中的另一个数据替换一个文件中的数据?

无法在 OpenBSD 上使用 editline 进行编译

arrays - 查找一个数字是否在排序数组中出现 n/2 次的最小复杂度

c - 函数的返回值对于变量和数组的行为有何不同

javascript - Ruby 中的索引

c - 对 'WinMain' 的 undefined reference [错误] ld 返回 1 退出状态,将矩阵作为函数中的参数传递

对 poll() 和 recvfrom() 的混淆