对于一项作业,我需要为 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;
}
至于用于对数组进行排序的代码,则它是无效的并且没有意义。至少变量 argument1
和 argument2
没有声明。
关于c - 使用交换函数交换二维数组指针中的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49476057/