Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2019
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. // arbitrary buffer size for reading file input
  5. #define BUFSIZE 1000
  6.  
  7. int find_array_maxes(int *input_array, int size){
  8. int max = 0;
  9. for(int i=0; i < size; i++){
  10. if(max < *input_array){
  11. max = *input_array;
  12. }
  13. input_array++;
  14. }
  15. return max;
  16. }
  17.  
  18. int main(int argc, char *argv[]){
  19. // check to ensure there are sufficient command line arguments
  20. if(argc <= 2){
  21. printf("At least two arguments are required!\n");
  22. exit(1);
  23. } else if(atoi(argv[1]) < 1){
  24. printf("You must create an array of at least 1 element!\n");
  25. exit(1);
  26. }
  27.  
  28. // allocates memory for array that will store file values
  29. int array_size = atoi(argv[1]);
  30. int *array_ptr = (int*) malloc(array_size * sizeof(int));
  31.  
  32. // creates a file ptr and buffer to read file contents
  33. FILE *file = fopen(argv[2], "r");
  34. char buff[BUFSIZE];
  35. int converted_num;
  36. int counter = 0;
  37.  
  38. // verify the array is allocated
  39. if(array_ptr == NULL){
  40. printf("Memory allocation of %d integer elements has failed.\n", array_size);
  41. fclose(file);
  42. exit(1);
  43. }
  44.  
  45. // stores contents of file into the buffer and is converted from the buffer to int
  46. // to be stored in the dynamically allocated array
  47. while(fgets(buff, BUFSIZE-1, file) != NULL && counter < array_size){
  48. converted_num = atoi(buff);
  49. *array_ptr = converted_num;
  50. printf("%d\n", *array_ptr);
  51. array_ptr++;
  52. counter++;
  53. }
  54.  
  55. array_ptr -= counter;
  56.  
  57. fclose(file);
  58.  
  59. int max1 = find_array_maxes(array_ptr, counter);
  60.  
  61. for(int i=0; i<counter; i++){
  62. if(max1 == *array_ptr){
  63. *array_ptr = 0;
  64. }
  65. array_ptr++;
  66. }
  67.  
  68. array_ptr -= counter;
  69.  
  70. int max2 = find_array_maxes(array_ptr, counter);
  71.  
  72. printf("The first max is %d and the second max is %d.\n", max1, max2);
  73. return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement