luishenriique

Aloção de memória com matrizes

Sep 5th, 2012
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.38 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <malloc.h>
  3.  
  4. void somar_matrizes(int, int, int, int, int);
  5.  
  6. int main(){
  7.     int *M1, *M2, *M3, LINHAS, COLUNAS;
  8.     int i, j, x;
  9.  
  10.     printf("Informe numero de linhas: ");
  11.     scanf("%d", &LINHAS);
  12.     printf("Informe o numero de colunas: ");
  13.     scanf("%d", &COLUNAS);
  14.  
  15.     if(LINHAS > 0 && COLUNAS > 0){
  16.         M1 = (int *) malloc (LINHAS*COLUNAS*sizeof(int));
  17.         if(M1 == NULL){
  18.             printf("Nao ha memoria disponivel.\n");
  19.             return 0;
  20.         }else{
  21.             printf("\nM1[%dx%d]\n\n", LINHAS, COLUNAS);
  22.             for(i = 0; i < LINHAS; i++){
  23.                 for(j = 0; j < COLUNAS; j++){
  24.                     printf("Informe M[%d][%d]: ", i, j);
  25.                     scanf("%d", M1 + i*COLUNAS+j);
  26.                 }
  27.             }
  28.         }
  29.  
  30.         printf("%d", M1 + i*COLUNAS+j);
  31.  
  32.         free(M1);
  33.  
  34.         M2 = (int *) malloc (LINHAS*COLUNAS*sizeof(int));
  35.         if(M2 == NULL){
  36.             printf("Nao ha memoria disponivel.\n");
  37.             return 0;
  38.         }else{
  39.             printf("\nM2[%dx%d]\n\n", LINHAS, COLUNAS);
  40.             for(i = 0; i < LINHAS; i++){
  41.                 for(j = 0; j < COLUNAS; j++){
  42.                     printf("Informe M[%d][%d]: ", i, j);
  43.                     scanf("%d", M2 + i*COLUNAS+j);
  44.                 }
  45.             }
  46.         }
  47.         free(M2);
  48.     }else{
  49.         printf("Matriz nula [0x0]\n");
  50.         return 0;
  51.     }
  52.  
  53.    
  54.  
  55.     printf("\n\n");
  56.     return 0;
  57. }
  58.  
  59. void somar_matrizes(int *M1, int *M2, int *M3, int LINHAS, int COLUNAS){
  60.     int i, j;
  61.     for (i=0; i<LINHAS; i++)
  62.     for (j=0; j<COLUNAS; j++)
  63.     *(M3+(i*COLUNAS+j)) = *(M1+(i*COLUNAS+j))+*(M2+(i*COLUNAS+j));
  64. }
Advertisement
Add Comment
Please, Sign In to add comment