在二维数组的主对角线上交换值 - C.

时间:2022-01-10 21:36:26

so this is part of my homework assignment. need some help with it. my task is to swap rows and columns so that the numbers on the main diagonal of a matrix are in descending order. the number of rows and columns is the same. also I need to allocate memory dynamically.

所以这是我的家庭作业的一部分。需要一些帮助。我的任务是交换行和列,以便矩阵的主对角线上的数字按降序排列。行数和列数是相同的。我还需要动态分配内存。

here is an example: input:

这是一个例子:输入:

    1 2       1<4 so we swap rows and columns and the final result is 4 3 
    3 4                                                               2 1

THE PROBLEM is that when I insert a 3x3 array or even larger I get some kind of a segmentation fault. here is my code, please help!

问题是,当我插入3x3阵列甚至更大时,我会遇到某种分段故障。这是我的代码,请帮忙!

    int **t, n, i, j, aux;
    printf("Insert the size of the matrix: ");
    scanf("%d",&n);

    t = malloc(n * sizeof(int *));

    for(i=1; i <= n; i++){
            t[i]=malloc(n * sizeof(int));
    }
    for(i=1; i<=n; i++){
            for(j=1; j<=n; j++){
                    printf("Element [%d][%d] : ", i, j);
                    scanf("%d", &t[i][j]);
            }
    }

    for(i=2; i<=n; i++){
            if(t[i][i] > t[i-1][i-1]){
                    j=i-1;
                    for(i=1; i<=n; i++){
                            aux=t[i][j];
                            t[i][j]=t[i][j+1];
                            t[i][j+1]=aux;
                    }
                    i=j;
                    for(j=1; j<=n; j++){
                            aux=t[i][j];
                            t[i][j]=t[i+1][j];
                            t[i+1][j]=aux;
                    }
                    i=1;
            }
    i++;
    }
    for(i=1; i<= n; i++){
            free(t[i]);
    }
    free(t);

Now the error I get is the following:

现在我得到的错误如下:

    The matrix inserted:
     1  2  3
     4  5  6
     7  8  9
    The matrix after swapping:
     5  4  6
     2  1  3
     8  7  9
    *** glibc detected *** ./6: double free or corruption (out): 0x08e42018 ***
    ======= Backtrace: =========
    /lib/i686/cmov/libc.so.6[0xb7649764]
    /lib/i686/cmov/libc.so.6(cfree+0x96)[0xb764b966]
    ./6[0x80488fb]
    ....

Thank you in advance!!

先谢谢你!!

1 个解决方案

#1


4  

Array indexes start from 0 to n-1, if it's size is n. With that said, you have quite a few places to take care of it. Play safe with array indexes. For example -

如果数组的大小为n,则数组索引从0开始到n-1。话虽如此,你有很多地方可以照顾它。使用数组索引安全播放。例如 -

for(i=1; i <= n; i++){  // Should be i=0; i < n; i++ 
        t[i]=malloc(n * sizeof(int));
}

#1


4  

Array indexes start from 0 to n-1, if it's size is n. With that said, you have quite a few places to take care of it. Play safe with array indexes. For example -

如果数组的大小为n,则数组索引从0开始到n-1。话虽如此,你有很多地方可以照顾它。使用数组索引安全播放。例如 -

for(i=1; i <= n; i++){  // Should be i=0; i < n; i++ 
        t[i]=malloc(n * sizeof(int));
}