C指针二维移至顶部

标签 c arrays pointers

总的来说,我对指针和 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/

相关文章:

c - 我们如何在没有getch()的情况下使用linux中的系统调用执行密码提示操作(对我们输入的每个字符立即显示*)?

c - 是否可以在不再次打印的情况下修改打印的字符串?

ios - Swift - 从 String 获取信息到 NSMutableArray

javascript - 如何访问 JavaScript 对象的数组属性

c - 为什么 'dereference' 和 'address of' 运算符在左边?

c - 为什么这个指针运算不起作用?

c - GCC ARM 链接器错误 - 未定义对 'strcmp' 的引用

javascript - 延迟显示 forEach 循环中的数组元素

c++ - 空指针如何改变它的值?

ios - 将 NSStrings 转换为 C 字符并从 Objective-C 调用 C 函数