如何删除0值和缩小数组?

时间:2018-03-03 20:40:23

标签: c arrays pointers malloc calloc

我的源代码:

#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

如何添加缩小功能,例如:如果用户输入的零的数量大于5,则缩小功能会删除它们并移位元素?

0 个答案:

没有答案