0

I'm trying to make function for transposing matrix.

Here I create a matrix, passing it to my function and got "segmentation fault" on line 20, but I can't figure out why, please help. I'm (almost) sure I not get out from allocated memory, and I'm passing matrix as "int ***"... For simplicity didn't make here memory free and output.

Also, I'll be glad for any comments and tips about this code.

#include <stdlib.h>

void transpose(int ***matrix, int *n, int *m) {
    // create additional matrix
    int **new_matrix = malloc(sizeof(int *) * (*m));
    for (int i = 0; i < *m; i++)
        new_matrix[i] = malloc(sizeof(int) * (*n));
    // store data in new matrix tranposing it
    for (int i = 0; i < *m; i++)
        for (int j = 0; j < *n; j++)
            new_matrix[i][j] = (*matrix)[j][i];
    // realloc initial matrix to fit transposed matrix
    for (int i = 0; i < *m; i++)
        (*matrix)[i] = realloc(*matrix, sizeof(int) * (*n));
    *matrix = realloc(*matrix, sizeof(int *) * (*m)); 
    // trying to write data from new array to initial
    for (int i = 0; i < *m; i++)
        for (int j = 0; j < *n; j++)
    // got segmentation fault here:
            (*matrix)[i][j] = new_matrix[i][j];
}

int main() {
    // create array: 0 1 2
    //               3 4 5
    int n = 2, m = 3;
    int **matrix = malloc(sizeof(int *) * n);
    for (int i = 0; i < n; i++)
        matrix[i] = malloc(sizeof(int) * m);
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
            matrix[i][j] = i * m + j;
    // trying to transpose:
    transpose(&matrix, &n, &m);
    return 0;
}

1 Answers1

1

(*matrix)[i] = realloc(*matrix, sizeof(int) * (*n)); doesn't make any sense, you need to do (*matrix)[i].

Also this code is very inefficient. Check out Correctly allocating multi-dimensional arrays.

Lundin
  • 195,001
  • 40
  • 254
  • 396