Advertisement
STANAANDREY

rev dyn arr

Feb 13th, 2023
951
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.89 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #define STEP 256
  4.  
  5. void checkAlloc(void *p) {
  6.   if (p == NULL) {
  7.     perror(NULL);
  8.     exit(-1);
  9.   }
  10. }
  11.  
  12. typedef struct {
  13.   int len, mem, *at;
  14. } DynArr;
  15.  
  16. void addToArr(DynArr *arr, int x) {
  17.   if (arr->len == arr->mem) {
  18.     arr->mem += STEP;
  19.     arr->at = realloc(arr->at, sizeof(int) * arr->mem);
  20.   }
  21.   arr->at[arr->len++] = x;
  22. }
  23.  
  24. void revArr(DynArr *arr) {
  25.   int len = arr->len;
  26.   for (int i = 0; i < len / 2; i++) {
  27.     int aux = arr->at[i];
  28.     arr->at[i] = arr->at[len - i - 1];
  29.     arr->at[len - i - 1] = aux;
  30.   }
  31. }
  32.  
  33. void printArr(const DynArr *const arr) {
  34.   for (int i = 0; i < arr->len; i++) {
  35.     printf("%d ", arr->at[i]);
  36.   }
  37.   puts("");
  38. }
  39.  
  40. int main(void) {
  41.   DynArr arr = {0, 0, NULL};
  42.   for (int x; scanf("%d", &x) && x;) {
  43.     addToArr(&arr, x);
  44.   }
  45.   revArr(&arr);
  46.   printArr(&arr);
  47.   free(arr.at);
  48.   return 0;
  49. }
  50.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement