asmodeus94

malloc

May 8th, 2015
267
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.98 KB | None | 0 0
  1. #include "stdafx.h"
  2. #include <conio.h>
  3. #include <stdlib.h>
  4.  
  5.  
  6. void DrawArray(int **t, int y, int x)
  7. {
  8.     int j;
  9.     for(int i = 0 ; i < y ; i++)
  10.     {
  11.         for(j = 0 ; j < x ; j++)
  12.         {
  13.             printf("%d %s", t[i][j],"\t");
  14.         }
  15.         printf("%s","\n");
  16.     }
  17. }
  18.  
  19. int** AllocArray(int y, int x)
  20. {
  21.     int **wsk = (int**)malloc(y * sizeof(int*));
  22.     for(int i = 0 ; i < y ; i++)
  23.     {
  24.         wsk[i] = (int*)malloc(x * sizeof(int));
  25.     }
  26.     return wsk;
  27. }
  28.  
  29. void DestroyArray(int **t, int y)
  30. {
  31.     for(int i = 0 ; i < y ; i++)
  32.         free(t[i]);
  33.     free(t);
  34. }
  35.  
  36. int _tmain(int argc, _TCHAR* argv[])
  37. {
  38.     int j = 1, rx, ry;
  39.     int **tab;
  40.  
  41.     printf("Podaj y (liczba wierszy): ");
  42.     scanf_s("%d", &ry);
  43.     printf("Podaj x (liczba kolumn): ");
  44.     scanf_s("%d", &rx);
  45.  
  46.     tab = AllocArray(ry, rx);
  47.    
  48.     for(int i = 0 ; i < ry ; i++)
  49.     {
  50.         for(j = 0 ; j < rx ; j++)
  51.         {
  52.             // y, x - najpierw numer "wiersza"
  53.             tab[i][j] = i * j;
  54.         }
  55.        
  56.     }
  57.     DrawArray(tab, ry, rx);
  58.     DestroyArray(tab, ry);
  59.     getchar();
  60.     getchar();
  61.     return 0;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment