简体   繁体   English

在 C 中分配二维 integer 数组

[英]Allocating a 2d integer array in C

I'm trying to dynamically allocate a 2D INT array in C in order to return a transposed matrix, I've done several research on the topic, and it should work this way, however I keep struggling with the program.我正在尝试在 C 中动态分配一个 2D INT 数组以返回一个转置矩阵,我已经对该主题进行了多项研究,它应该以这种方式工作,但是我一直在努力解决这个程序。

I tried it many different ways now (offset, pointer arithmetic), I didn't find a fix for the problem.我现在尝试了很多不同的方法(偏移量,指针算法),我没有找到解决问题的方法。

I'm either getting trash values or the program crashes (no seg fault, error code crash).我要么得到垃圾值,要么程序崩溃(没有段错误,错误代码崩溃)。

I'm also loooking for a proper version to allocate the memory, I've seen several versions on stackoverflow, the one I would preferrably like to use, is allocating pointer space and the integer space afterwards (the one I'm trying to use in the example below).我也在寻找一个合适的版本来分配 memory,我在 stackoverflow 上看到了几个版本,我更喜欢使用的版本是分配指针空间和 integer 空间之后(我正在尝试使用的那个)在下面的示例中)。

   // Convert a matrix to it's transposed version. Returns a two dimensional array (pointer)
int **getTransposedMatrix(int *matrix, int dimension_h, int dimension_w){
    int **transposedMatrix = (int **) malloc(dimension_w * sizeof(int*));

    for(int row=0; row<dimension_w; row++){
        transposedMatrix[row] = (int*) malloc(dimension_w * sizeof(int));
    }

    for(int row=0; row<dimension_h; row++){
        for(int column=0; column<dimension_w; column++){
            transposedMatrix[column][row] = *(matrix + row * dimension_w + column);
         printf("%d ", transposedMatrix + (row * dimension_w + column));
        }
        printf("\n");
    }
    return **transposedMatrix;
}

I appreciate any help:)我很感激任何帮助:)

I would not bother with a "2D array" such as the one you are setting up, where you're allocating the rows separately.我不会打扰“二维数组”,例如您正在设置的那个,您在其中分别分配行。 Below is my version which uses a single array and calculates offsets into it accordingly.下面是我的版本,它使用单个数组并相应地计算其中的偏移量。

int *getTransposedMatrix(int *matrix, int dimension_w, int dimension_h)
{
    int *transposed = malloc(dimension_w * dimension_h * sizeof(int));
    for (int row = 0; row < dimension_h; row++) {
        for (int col = 0; col < dimension_w; col++) {
            transposed[col * dimension_h + row] = matrix[row * dimension_w + col];
        }
    }
    return transposed;
}

ideone with some test examples ideone 有一些测试示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM