You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

69 lines
1.6 KiB

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. // Assuming that previous size is provided, since there is no standard way to know the size of the allocated block
  5. void* myrealloc(void* ptr, size_t prev_size, size_t new_size) {
  6. if (ptr == NULL) prev_size = 0;
  7. char *res = malloc(new_size);
  8. size_t copy_size = (prev_size < new_size ? prev_size : new_size);
  9. for (size_t i = 0; i < copy_size; ++i) {
  10. res[i] = ((char*) ptr)[i];
  11. }
  12. free(ptr);
  13. return res;
  14. }
  15. // Copied and fixed the code from goo.gl/EMpzYz
  16. // test myrealloc using ex3
  17. int main() {
  18. //Allows you to generate random number
  19. srand(time(NULL));
  20. // Allows user to specify the original array size, stored in variable n1.
  21. printf("Enter original array size:");
  22. int n1=0;
  23. scanf("%d",&n1);
  24. //Create a new array of n1 ints
  25. int* a1 = malloc(sizeof(int) * n1);
  26. int i;
  27. for(i=0; i<n1; i++){
  28. //Set each value in a1 to 100
  29. a1[i]=100;
  30. //Print each element out (to make sure things look right)
  31. printf("%d ", a1[i]);
  32. }
  33. //User specifies the new array size, stored in variable n2.
  34. printf("\nEnter new array size: ");
  35. int n2=0;
  36. scanf("%d",&n2);
  37. //Dynamically change the array to size n2
  38. a1 = myrealloc(a1, sizeof(int) * n1, sizeof(int) * n2);
  39. //If the new array is a larger size, set all new members to 0. Reason: dont want to use uninitialized variables.
  40. for (int i = n1; i < n2; ++i) {
  41. a1[i] = 0;
  42. }
  43. for(i=0; i<n2;i++){
  44. //Print each element out (to make sure things look right)
  45. printf("%d ", a1[i]);
  46. }
  47. printf("\n");
  48. //Done with array now, done with program :D
  49. free(a1);
  50. return 0;
  51. }