0

My source code:

#include<stdio.h>
#include<stdlib.h>
int main() {
  int val, n = 2, i = 0;
  int *arr = (int *) calloc(5, sizeof(int));

  while (1 == 1) {
    printf("Enter the value for array: ");
    scanf("%d", &val);
    arr[i] = val;
    printf("arr[%d]=%d\n", i, arr[i]);
    i++;
    if (i % 5 == 0) {
      int ans1;
      printf("Do you want expand array?\n");
      scanf("%d", &ans1);
      if (ans1 == 1) {
        arr = (int *) realloc(arr, n * 5 * sizeof(int));
        n++;
      } //end inner if
    } //end inner if 
    for (int j = 0; j < i; j++)
      printf("arr[%d]=%d\n", j, arr[j]); 
} //end while

} //end main

How can I add shrink function like for instance: if count of zeros entered by user is more than 5, shrink function will delete them and shift elements?

Bsquare ℬℬ
  • 4,423
  • 11
  • 24
  • 44
  • 4
    "How to ... and shrink array?" --> To be clear, in C, once an array if defined, it size cannot change. Yet `arr` is not an _array_, but a _pointer_ with a value to allocated memory. The pointer value and allocation size can change. – chux - Reinstate Monica Mar 03 '18 at 20:47
  • you can just do `while(1)` (or `while(true)` if you `#include `, but I don't know off the top what version of C introduced `stdbool.h`) – yano Mar 03 '18 at 20:47
  • 1
    You use two pointers: a reader and a writer. Both pointers start at the beginning of the sequence. The reader advances up the sequence one slot per iteration. If the value pointed to by the reader is *not* zero, you write it to the slot pointed to by the writer pointer, then increment the writer. Otherwise leave the writer as is and continue on. When done, the writer will be pointing to one-past the last item in the sequence. From that, sizing can be done and you can shrink as warranted if your sequence was dynamic. – WhozCraig Mar 03 '18 at 20:51
  • Seyid Alibeyli, I re-formatted for clarity and found `{}` to not line up. Please edit post to reflect your true compilable code. – chux - Reinstate Monica Mar 03 '18 at 20:54
  • 3
    @yano `` came in 19 years ago with C99. – chux - Reinstate Monica Mar 03 '18 at 20:55
  • You haven't posted any code that tries to do what you are asking, wondering maybe, how to do. – R Sahu Mar 03 '18 at 21:18
  • There is no need to cast the return of `malloc`, it is unnecessary. See: [**Do I cast the result of malloc?**](http://stackoverflow.com/q/605845/995714). And if you don't check the return of `scanf("%d", &val);` and `scanf("%d", &ans1);`, you risk invoking *Undefined Behavior* when you access `val` or `ans1`. – David C. Rankin Mar 03 '18 at 23:30
  • `while (1 == 1)` -> `for (;;)` – chqrlie Mar 03 '18 at 23:37

0 Answers0