总的来说,我对指针和 C 还很陌生。
void moveUpToTop(int num, int dim, int index) {
int i,j;
double *temp = w[index];
double *zero = w[0];
for(i = index; i > 0; i--) {
double *ptrA = w[i];
double *ptrB = w[i - 1];
for(j = 0; j < dim; j++) {
*(ptrA + j) = *(ptrB + j);
}
}
for(j = 0; j < dim; j++) {
*(zero + j) = *(temp + j);
}
}
将其与二维数组 w 一起使用,定义为 double **w。我想使用指针将一些带有索引“index”的数组值移动到数组的顶部,因为这是我们必须做的练习。
首先,我保存一个数组位置,然后将所有数组位置上移一级。 我做错了什么?
给我的是下面的代码,我必须设计排序函数。
double **w;
int main (void) {
int dim, num;
int i, j;
scanf ("%d %d", &dim, &num);
w = calloc (num, sizeof (double *));
for (i = 0; i < num; i++) {
w[i] = calloc (dim + 1, sizeof (double));
int sum = 0;
for (j = 0; j < dim; j++) {
scanf ("%le", &w[i][j]);
sum += w[i][j] * w[i][j];
}
w[i][dim] = sqrt(sum);
}
sort(num, dim);
for(i = 0; i < num; i++) {
for(j = 0; j < dim; j++) {
printf("%e ", w[i][j]);
}
printf("\n");
}
return 0;
}
最佳答案
您的问题是您保存了指向原始数据的指针,但没有保存数据本身。
double *temp = w[index]; // Here you save the pointer
但在第一个循环中您会覆盖数据:
for(i = index; i > 0; i--) {
double *ptrA = w[i]; // Same as w[index] in first loop
double *ptrB = w[i - 1];
for(j = 0; j < dim; j++) {
*(ptrA + j) = *(ptrB + j); // The data pointed to by w[index] is overwritten
// in the first loop
所以这段代码没有复制索引处的原始数据:
for(j = 0; j < dim; j++) {
*(zero + j) = *(temp + j); // Data at index have been overwritten
// so this doesn't do what you want
}
要解决此问题,仅保存指向 index
的指针(即 double *temp = w[index];
)是不够的。相反,您需要保存 double *temp = w[index];
指向的所有数据。
因此,您需要malloc
一些数据来保存副本。然后在for循环中复制数据,并在恢复到零
时使用复制的数据。
顺便说一句:另请注意,给您的代码使用了非常丑陋的构造。它分配 dim + 1
来保存额外的 double 。因此,您的移动函数还需要使用 dim + 1
而不仅仅是 dim
关于C指针二维移至顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43054413/