问题描述
对于一项分配,我需要对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.
我的问题是我似乎无法完成指针所包含地址的交换。我已经在SO中搜索了相关问题,但是它们几乎都改变了指针所指位置的值。
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:
交换功能
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;
}
当我测试此程序时,它确实正确输入了交换功能,但打印结果与输入相同(因此未交换)。谁能帮我为什么这不起作用?
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?
推荐答案
交换功能看起来像
void swap( double **p, double **q )
{
double *tmp = *p;
*p = *q;
*q = tmp;
}
至于用于对数组进行排序的代码无效,并且没有道理。至少未声明变量 argument1
和 argument2
。
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.
这篇关于使用交换功能交换2D数组指针中的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!