fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. /* Return a pointer to an array of two dynamically allocated arrays of ints.
  5.   The first array contains the elements of the input array s that are
  6.   at even indices. The second array contains the elements of the input
  7.   array s that are at odd indices.
  8.  
  9.   Do not allocate any more memory than necessary. You are not permitted
  10.   to include math.h. You can do the math with modulo arithmetic and integer
  11.   division.
  12. */
  13. int **split_array(const int *s, int length) {
  14. length--;
  15. int **result = malloc(2 * sizeof(int));
  16. int *odd, *even;
  17. if (length % 2 == 0) {
  18. result[0] = (int*) malloc((length / 2) * sizeof(int));
  19. result[1] = (int*) malloc((length / 2) * sizeof(int));
  20. } else {
  21. int even_count = (length + 1) / 2;
  22. result[0] = malloc(even_count * sizeof(int));
  23. result[1] = malloc((length - even_count) * sizeof(int));
  24. }
  25. even = &result[0][0], odd = &result[1][0];
  26. for (int a = 0; a < length; a++) {
  27. if (a % 2 == 0) {
  28. *even = s[a];
  29. even++;
  30. } else {
  31. *odd = s[a];
  32. odd++;
  33. }
  34. }
  35. return result;
  36. }
  37.  
  38. /* Return a pointer to an array of ints with size elements.
  39.   - strs is an array of strings where each element is the string
  40.   representation of an integer.
  41.   - size is the size of the array
  42.  */
  43.  
  44. int *build_array(char **strs, int size) {
  45. size--;
  46. int *arr = malloc(size * sizeof(int));
  47. int *element = &arr[0];
  48. while (element < &arr[size]) {
  49. strs++;
  50. *element = **strs - '0';
  51. // printf("%d\n", *element);
  52. element++;
  53. }
  54. return arr;
  55. }
  56.  
  57.  
  58. int main(int argc, char **argv) {
  59. /* Replace the comments in the next two lines with the appropriate
  60.   arguments. Do not add any additional lines of code to the main
  61.   function or make other changes.
  62.   */
  63. int *full_array = build_array(argv, argc);
  64. int **result = split_array(full_array, argc);
  65.  
  66. printf("Original array:\n");
  67. for (int i = 0; i < argc - 1; i++) {
  68. printf("%d ", full_array[i]);
  69. }
  70. printf("\n");
  71.  
  72. printf("result[0]:\n");
  73. for (int i = 0; i < argc / 2; i++) {
  74. printf("%d ", result[0][i]);
  75. }
  76. printf("\n");
  77.  
  78. printf("result[1]:\n");
  79. for (int i = 0; i < (argc - 1) / 2; i++) {
  80. printf("%d ", result[1][i]);
  81. }
  82. printf("\n");
  83. free(full_array);
  84. free(result[0]);
  85. free(result[1]);
  86. free(result);
  87. return 0;
  88. }
  89.  
Success #stdin #stdout 0.01s 5276KB
stdin
1 2 3
stdout
Original array:

result[0]:

result[1]: