0

I'm working on a project in C that requires the transpose of a matrix. It has to be able to be used on a general matrix of the form mxn.When we run the function, it tells us that the transpose is a matrix of zeros. Help would be much appreciated! I should add that I'm new to C, so if its something obvious, sorry!

Here's the code:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

//fonction pour transposer une matrice
void transpose(float **matrice, float** matrice2, int m, int n){
    int i,j;

    //Allocation dynamique
    matrice2=(float**)malloc((4)*sizeof(float*));
    matrice2[0]=(float*)malloc(2*(4)*sizeof(float));

    for(i=1;i<4;i++){
    matrice2[i]=matrice2[i-1]+2;}

    //transpose
    for(j=0; j<m; j++){
        for(i=0; i<n; i++){
            matrice[j][i]=matrice2[i][j];
            }
        }
    }


int main(){
    float **A,**B;
    int i,j;

    //Allocation dynamique
    A=(float**)malloc((4)*sizeof(float*));
    A[0]=(float*)malloc(2*(4)*sizeof(float));
    B=(float**)malloc((4)*sizeof(float*));
    B[0]=(float*)malloc(2*(4)*sizeof(float));

    for(i=1;i<4;i++){
    A[i]=A[i-1]+2;
    B[i]=B[i-1]+2;}

    //Definition de matrice A
    A[0][0]=0.5;
    A[0][1]=0.25;
    A[1][0]=1;
    A[1][1]=2.2;

    //Impression de A
    for(i=0;i<2;i++){
        for(j=0;j<2;j++){
            printf("%f ", A[j][i]);}
            printf("\n");
            }

    //B = transposer A
    transpose(A,B,2,2);

    //Impression de B
    for(i=0;i<2;i++){
        for(j=0;j<2;j++){
            printf("%f ", B[j][i]);}
            printf("\n");
            }
    }
Cait
  • 9
  • 1
  • 5
    1) You don't allocate the pointer arrays correctly. 2) You shouldn't use pointer arrays in the first place, use 2D arrays instead. [Correctly allocating multi-dimensional arrays](http://stackoverflow.com/questions/42094465/correctly-allocating-multi-dimensional-arrays). – Lundin Apr 27 '17 at 14:23
  • 1
    Also, you need to pick a more conventional coding style and stick to it consistently. This code is very hard to read. – Lundin Apr 27 '17 at 14:25

0 Answers0