0
#include <stdlib.h>
void matriz_transposta( int l, int c, int *matriz);
int main (void){
int linha = 2, coluna = 2;
int *mat = (int*) malloc(linha*coluna*sizeof(int));
mat[0] = 1;
mat[1] = 2;
mat[2] = 3;
mat[3] = 4;
puts("Matriz original");
int i, j, k;
for ( i = 0; i < linha; i++)
for(j = 0; j < coluna; j++){
k = i * linha+j;
printf("%d ", mat[k]);
}
matriz_transposta(linha, coluna, mat);
puts("\n");
puts("Matriz transposta");
for ( i = 0; i < linha; i++)
for(j = 0; j < coluna; j++){
k = i * linha+j;
printf("%d ", mat[k]);
}
}
void matriz_transposta( int l, int c, int *matriz){
int i, j, k;
int *ptraux = (int *) malloc(l*c*sizeof(int));
puts("\n");
for (i = 0; i < l; i ++)
for ( j = 0; j < c; j++){
ptraux[i*l+j] = matriz[j*l+i];
printf("%d ", ptraux[i*l+j]);
}
matriz = ptraux;
puts("\n");
for ( i = 0; i < l; i++)
for(j = 0; j < c; j++){
k = i * l+j;
printf(" %d ", matriz[k]);
}
free(ptraux);
}
When you do
matriz = ptraux
, you are just changing the local value of the pointer within the function. You need to either modify the original matrix itself within the function, or copy the entire contents of the helper to the original (for example, withmemcpy(matriz, ptraux, sizeof(int) * l * c)
).– bfavaretto