Advertisement
KuoHsiangYu

林鈺錦_二維陣列3

Oct 23rd, 2018
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.06 KB | None | 0 0
  1. //詢問 malloc 操作二維指標 陣列 以及free的方法
  2. //https://www.facebook.com/xiangyu.guo1/posts/1978306308864247?comment_id=2238759159485626&comment_tracking=%7B%22tn%22%3A%22R%2399%22%7D
  3. //https://www.facebook.com/groups/1403852566495675/permalink/2067257373488521/
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7.  
  8. void print_array(int **a, int x, int y)
  9. {
  10.     for (int i = 0; i < x; i++)
  11.     {
  12.         for (int j = 0; j < y; j++)
  13.         {
  14.             printf("%d, ", a[i][j]);
  15.         }
  16.         printf("\n");
  17.     }
  18. }
  19.  
  20. // 初始化陣列的函式,可以指定陣列大小
  21. int **init_array(int x, int y)
  22. {
  23.     // 初始化第一維
  24.     int **a = (int **)malloc(sizeof(int *) * x);
  25.  
  26.     // 初始化每個第一維的第二維
  27.     for (int i = 0; i < x; i++)
  28.     {
  29.         a[i] = (int *)malloc(sizeof(int) * y);
  30.     }
  31.     return a;
  32. }
  33.  
  34. int main(void)
  35. {
  36.     int **a = init_array(2, 2);
  37.  
  38.     //給值,實際上給值進陣列的應該會是一個函式,也可以跟初始化陣列的函式寫在一起
  39.     a[0][0] = 0, a[0][1] = 1, a[1][0] = 2, a[1][1] = 3;
  40.  
  41.     print_array(a, 2, 2);
  42.     system("pause");
  43.     return 0;
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement