vararr2d.c 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. //vararr2d.c -- functions using VLAs
  2. #include <stdio.h>
  3. #define ROWS 3
  4. #define COLS 4
  5. int sum2d(int rows, int cols, int ar[rows][cols]);
  6. int main(void)
  7. {
  8. int i, j;
  9. int rs = 3;
  10. int cs = 10;
  11. int junk[ROWS][COLS] = {
  12. {2,4,6,8},
  13. {3,5,7,9},
  14. {12,10,8,6}
  15. };
  16. int morejunk[ROWS-1][COLS+2] = {
  17. {20,30,40,50,60,70},
  18. {5,6,7,8,9,10}
  19. };
  20. int varr[rs][cs]; // VLA
  21. for (i = 0; i < rs; i++)
  22. for (j = 0; j < cs; j++)
  23. varr[i][j] = i * j + j;
  24. printf("3x5 array\n");
  25. printf("Sum of all elements = %d\n",
  26. sum2d(ROWS, COLS, junk));
  27. printf("2x6 array\n");
  28. printf("Sum of all elements = %d\n",
  29. sum2d(ROWS-1, COLS+2, morejunk));
  30. printf("3x10 VLA\n");
  31. printf("Sum of all elements = %d\n",
  32. sum2d(rs, cs, varr));
  33. return 0;
  34. }
  35. // function with a VLA parameter
  36. int sum2d(int rows, int cols, int ar[rows][cols])
  37. {
  38. int r;
  39. int c;
  40. int tot = 0;
  41. for (r = 0; r < rows; r++)
  42. for (c = 0; c < cols; c++)
  43. tot += ar[r][c];
  44. return tot;
  45. }