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.

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).

   // 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 :)

Upvotes: 0

Views: 97

Answers (1)

vmt
vmt

Reputation: 860

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

Upvotes: 1

Related Questions