Advertisement
Guest User

Untitled

a guest
Mar 19th, 2019
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #define NUM_ROWS 3
  5.  
  6. int main() {
  7. /**
  8. * In this demo, we'll be creating an irregular 2D array with 3 rows.
  9. */
  10. int **array = NULL;
  11. int numCols;
  12.  
  13. int len[3]; // array to store row length for printing only, you can disregard this
  14.  
  15. // 1. First Dimension
  16. array = (int**) malloc(sizeof(int *) * NUM_ROWS);
  17.  
  18. // 2. Second Dimension
  19. for (int row = 0; row < NUM_ROWS; row++) {
  20. do {
  21. // Prompt for number of rows
  22. printf("Number of columns for row %i: ", row + 1);
  23. scanf("%i", &numCols);
  24.  
  25. len[row] = numCols; // store current number; disregard this
  26. } while (numCols < 1);
  27.  
  28. // Allocate number of row
  29. array[row] = (int*) malloc(sizeof(int) * numCols);
  30.  
  31. // Pre-fill array
  32. for (int col = 0; col < numCols; col++) {
  33. array[row][col] = numCols;
  34. }
  35. }
  36.  
  37. // Printing
  38. printf("\n");
  39. for (int row = 0; row < NUM_ROWS; row++) {
  40. printf("ROW %i: ", row + 1);
  41. for (int col = 0; col < len[row]; col++) {
  42. printf("[%2i] ", array[row][col]);
  43. }
  44. printf("\n");
  45. }
  46.  
  47. // Freeing
  48. for (int row = 0; row < NUM_ROWS; row++) {
  49. free(array[row]);
  50. }
  51.  
  52. return 0;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement