25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

68 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. // test myrealloc using ex3
  16. int main() {
  17. //Allows you to generate random number
  18. srand(time(NULL));
  19. // Allows user to specify the original array size, stored in variable n1.
  20. printf("Enter original array size:");
  21. int n1=0;
  22. scanf("%d",&n1);
  23. //Create a new array of n1 ints
  24. int* a1 = malloc(sizeof(int) * n1);
  25. int i;
  26. for(i=0; i<n1; i++){
  27. //Set each value in a1 to 100
  28. a1[i]=100;
  29. //Print each element out (to make sure things look right)
  30. printf("%d ", a1[i]);
  31. }
  32. //User specifies the new array size, stored in variable n2.
  33. printf("\nEnter new array size: ");
  34. int n2=0;
  35. scanf("%d",&n2);
  36. //Dynamically change the array to size n2
  37. a1 = myrealloc(a1, sizeof(int) * n1, sizeof(int) * n2);
  38. //If the new array is a larger size, set all new members to 0. Reason: dont want to use uninitialized variables.
  39. for (int i = n1; i < n2; ++i) {
  40. a1[i] = 0;
  41. }
  42. for(i=0; i<n2;i++){
  43. //Print each element out (to make sure things look right)
  44. printf("%d ", a1[i]);
  45. }
  46. printf("\n");
  47. //Done with array now, done with program :D
  48. free(a1);
  49. return 0;
  50. }