Advertisement
Savior

Два способа выделения памяти для двумерного массива функцией

Dec 11th, 2013
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.88 KB | None | 0 0
  1. #include <cstdio>
  2.  
  3. void reserveMemory(int ***a, int x, int y)
  4. {
  5.     *a = (int **)malloc(sizeof(int*) * x);
  6.     for (int i = 0; i < x; i++)
  7.         (*a)[i] = (int *)malloc(sizeof(int) * y);
  8.        
  9.     for (int i = 0; i < x; i++)
  10.         for (int j = 0; j < y; j++)
  11.             (*a)[i][j] = (i * y) + j + 1;
  12. }
  13.  
  14. int **reserveMemory2(int x, int y)
  15. {
  16.     int **a = (int **)malloc(sizeof(int*) * x);
  17.     for (int i = 0; i < x; i++)
  18.         a[i] = (int *)malloc(sizeof(int) * y);
  19.        
  20.     for (int i = 0; i < x; i++)
  21.         for (int j = 0; j < y; j++)
  22.             a[i][j] = (i * y) + j + 1;
  23.            
  24.     return a;
  25. }
  26.  
  27. int main()
  28. {
  29.     int **a, **b;
  30.     reserveMemory(&a, 10, 10);
  31.     b = reserveMemory2(10, 10);
  32.     for (int i = 0; i < 10; i++) {
  33.         for (int j = 0; j < 10; j++)
  34.             printf("%d\t", a[i][j]);
  35.         printf("\n");
  36.     }
  37.     printf("\n");
  38.     for (int i = 0; i < 10; i++) {
  39.         for (int j = 0; j < 10; j++)
  40.             printf("%d\t", b[i][j]);
  41.         printf("\n");
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement