Advertisement
Guest User

Untitled

a guest
Dec 11th, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.81 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int main(void)
  5. {
  6. int **a; // why?
  7. int rows = 3, columns = 4;
  8.  
  9. /* Allocate memory for row pointers */
  10. if ((a = (int **)malloc(rows * sizeof(int *))) == NULL)
  11. exit(EXIT_FAILURE);
  12.  
  13. /* Allocate memory for rows */
  14. for (int y = 0; y < rows; y++)
  15. {
  16. if ((a[y] = (int *)malloc(columns * sizeof(int))) == NULL)
  17. exit(EXIT_FAILURE);
  18. }
  19.  
  20. /* Fill matrix with some data */
  21. for (int y = 0; y < rows; y++)
  22. {
  23. for (int x = 0; x < columns; x++)
  24. a[y][x] = 10 * (y + 1) + (x + 1);
  25. }
  26.  
  27. /* Print matrix to the console */
  28. for (int y = 0; y < rows; y++)
  29. {
  30. for (int x = 0; x < columns; x++)
  31. printf("%2d ", a[y][x]);
  32. putchar('\n');
  33. }
  34.  
  35. /* Free matrix memory */
  36. for (int y = 0; y < rows; y++)
  37. free(a[y]);
  38. free(a);
  39.  
  40. getchar();
  41. return 0;
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement