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.
 
 
 

53 lines
1.1 KiB

  1. // Copied and fixed the code from goo.gl/EMpzYz
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include <time.h>
  5. int main(){
  6. //Allows you to generate random number
  7. srand(time(NULL));
  8. // Allows user to specify the original array size, stored in variable n1.
  9. printf("Enter original array size:");
  10. int n1=0;
  11. scanf("%d",&n1);
  12. //Create a new array of n1 ints
  13. int* a1 = malloc(sizeof(int) * n1);
  14. int i;
  15. for(i=0; i<n1; i++){
  16. //Set each value in a1 to 100
  17. a1[i]=100;
  18. //Print each element out (to make sure things look right)
  19. printf("%d ", a1[i]);
  20. }
  21. //User specifies the new array size, stored in variable n2.
  22. printf("\nEnter new array size: ");
  23. int n2=0;
  24. scanf("%d",&n2);
  25. //Dynamically change the array to size n2
  26. a1 = realloc(a1, sizeof(int) * n2);
  27. //If the new array is a larger size, set all new members to 0. Reason: dont want to use uninitialized variables.
  28. for (int i = n1; i < n2; ++i) {
  29. a1[i] = 0;
  30. }
  31. for(i=0; i<n2;i++){
  32. //Print each element out (to make sure things look right)
  33. printf("%d ", a1[i]);
  34. }
  35. printf("\n");
  36. //Done with array now, done with program :D
  37. free(a1);
  38. return 0;
  39. }