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


typedef struct {
    int ncols;
    int nlins;
    int **data;
}* Matriz;

Matriz cria_matriz(int nlins,int ncols){
    Matriz M;
    M = malloc(sizeof(Matriz));
    M->ncols = ncols;
    M->nlins = nlins;
    
    (*M).data = malloc(sizeof(int*) * nlins);
    for (int i = 0 ; i < nlins ; i ++){
        M->data[i] = malloc(sizeof(int) * ncols);
    } 
    return M;
}

void le_matriz(Matriz M){
    for (int i = 0 ; i < M->nlins; i++ ){
        for(int j = 0 ; j< M->ncols;j++){
            scanf("%d",&M->data[i][j]);
        }
    }
}

void imprime_matriz(Matriz M){
    for (int i = 0 ; i < M->nlins; i++ ){
        for(int j = 0 ; j< M->ncols;j++){
            printf("%d ",M->data[i][j]);
        }
        printf("\n");
    }    
}

void libera_memoria(Matriz M){
    for (int i=0;i<M->nlins;i++){
        free(M->data[i]);
    }
    free(M->data);
    free(M);
}

void swap(Matriz *M1, Matriz *M2){
    // *A deve apontar para o endereco do ponteiro da matriz A
    printf("end: %p , para onde aponta:%p\n",M1,*M1);
    Matriz tmp = *M1;
    *M1 = *M2;
    *M2 = tmp;

}

int main() {
    int ncols,nlins;
    scanf("%d %d",&ncols,&nlins);
    Matriz A = cria_matriz(nlins,ncols);
    printf("endereco de A :%p\n",A);
    le_matriz(A);
    imprime_matriz(A);

    scanf("%d %d",&ncols,&nlins);
    Matriz B = cria_matriz(nlins,ncols);
    printf("endereco de B: %p\n",B);
    le_matriz(B);
    imprime_matriz(B);

    printf("Depois do SWAP\n");
    printf("%p, end do ponteiro: %p \n",A,&A);
    swap(&A,&B);
    printf("endereco de A :%p\n",A);
    imprime_matriz(A);
    printf("endereco de B: %p\n",B);
    imprime_matriz(B);

    libera_memoria(B);
    libera_memoria(A);

    return 0;
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: