Advertisement
Guest User

Untitled

a guest
Nov 20th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int main(int argc, char *argv[])
  5. {
  6. // Allocate memory for the array like this:
  7.  
  8. int** array;
  9.  
  10. array = malloc(n * sizeof(*array)); /* Assuming `n` is the number of rows */
  11. if(!array) /* If `malloc` failed */
  12. {
  13. fputs(stderr, ""Error allocating memory; Bailing out!"");
  14. exit(-1);
  15. }
  16.  
  17. int count = 1;
  18. for(int i = 0; i < n; i++)
  19. {
  20. array[i] = malloc(count * sizeof(**array));
  21. if(!array[i]) /* If `malloc` failed */
  22. {
  23. for(int j = 0; j < i; j++) /* free previously allocated memory */
  24. {
  25. free(array[j]);
  26. }
  27. free(array);
  28.  
  29. fputs(stderr, ""Error allocating memory; Bailing out!"");
  30. exit(-1);
  31. }
  32. count++;
  33. }
  34.  
  35. // Then, read data from the file into the array by using:
  36.  
  37. FILE* fp = fopen(""file.txt"", ""r"");
  38. if(!fp)
  39. {
  40. for(int i = 0; i < n; i++) /* free previously allocated memory */
  41. {
  42. free(array[i]);
  43. }
  44. free(array);
  45.  
  46. fputs(stderr, ""Error opening 'file.txt'; Bailing out!"");
  47. exit(-1);
  48. }
  49.  
  50. int max = 1;
  51.  
  52. for(int i = 0; i < n; i++)
  53. {
  54. for(count = 0; count < max; count++)
  55. {
  56. fscanf(fp, ""%d"", &array[i][count]);
  57. }
  58. max++;
  59. }
  60.  
  61. // Then print the results:
  62.  
  63. max = 1;
  64.  
  65. for(int i = 0; i < n; i++)
  66. {
  67. for(count = 0; count < max; count++)
  68. {
  69. printf(""array[%d][%d] = %d"", i, count, array[i][count]);
  70. }
  71. max++;
  72. }
  73.  
  74. // And finally, free the allocated memory:
  75.  
  76. for(int i = 0; i < n; i++)
  77. {
  78. free(array[i]);
  79. }
  80. free(array);
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement