Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 

51 rader
1.1 KiB

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