aptr.c 993 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. int main() {
  4. int i, j;
  5. /* TODO: define the 2D pointer variable here */
  6. int ** pnumbers;
  7. /* TODO: complete the following line to allocate memory for holding three rows */
  8. pnumbers = (int **) malloc(sizeof(int)*6);
  9. /* TODO: allocate memory for storing the individual elements in a row */
  10. pnumbers[0] = (int *) malloc(1 * sizeof(int));
  11. pnumbers[1] = (int *) malloc(2 * sizeof(int));
  12. pnumbers[2] = (int *) malloc(3 * sizeof(int));
  13. pnumbers[0][0] = 1;
  14. pnumbers[1][0] = 1;
  15. pnumbers[1][1] = 1;
  16. pnumbers[2][0] = 1;
  17. pnumbers[2][1] = 2;
  18. pnumbers[2][2] = 1;
  19. for (i = 0; i < 3; i++) {
  20. for (j = 0; j <= i; j++) {
  21. printf("%d", pnumbers[i][j]);
  22. }
  23. printf("\n");
  24. }
  25. for (i = 0; i < 3; i++) {
  26. /* TODO: free memory allocated for each row */
  27. free(pnumbers[i]);
  28. }
  29. /* TODO: free the top-level pointer */
  30. free(pnumbers);
  31. return 0;
  32. }