如何根据条件将一个数组中的元素添加到另一个未定义大小的数组中?

3

我已经自学了几周的C语言,并试图编写一段代码,使用户可以决定数组的大小和元素,然后将其分成两个数组 - 一个存储奇数,另一个存储偶数。

我相信动态分配与此有关,但我不知道如何实现。下面是目前的代码:

#include <stdio.h>
#include <stdlib.h>

int main()
{
  //User decides the size of the array of numbers-------------------------------
  int n;
  printf("How many numbers? ");
  scanf("%d",&n);

  //User inputs values into array the size of array[n]--------------------------
  int i;
  int array[n];
  printf("What are the numbers?\n");
  for(i=0; i<n; i++)
  {
    scanf("%d",&array[i]);
  }

  //loop goes through array, separates even and odds into 2 new arrays----------
  //use dynamic allocation??

  for(i=0;i<n;i++)
  {
    int *evenarray = malloc(sizeof(evenarray)); //not sure if this is setup correctly
    int *oddarray = malloc(sizeof(oddarray)); //not sure if this is setup correctly

    if(array[i] % 2 == 0) //if value in array CAN be divided by 2
    {
      printf("Test statement.\n");
    }
    else //if this is not true, append to odd array
    {
      printf("Second test statement.\n");
    }
  }
}

/*this program accepts a user chosen number of numbers
  then, the program separates the odd and even numbers into
  two different arrays*/
2个回答

3

没有什么神奇的方法能够一次性获取这些信息。 但是,您可以尝试以下两种方法之一:

  • 循环遍历第一个数组以确定奇数(或偶数)数字的计数,然后您就知道必须分配内存的元素计数,您可以使用 VLA(作为第一个数组本身)或使用指针和分配器函数来分配内存。

    --> 但是,在此过程中,您必须执行奇偶检查两次 - 一次用于计算奇/偶数出现的次数,下一次实际上要决定并将它们复制到新位置。

  • 分配两个类似于第一个数组大小的内存块,并开始将奇数和偶数元素分别填入新内存中。 存储所有元素后,对计数进行调整,realloc()已分配的内存大小。

    --> 在这种情况下,需要进行预分配,但只需要进行一次奇/偶检查。


-1
你可以将奇数和偶数分别复制到不同的数组中,并保持单独的计数器来跟踪它。例如:
  //loop goes through array, separates even and odds into 2 new arrays----------
  //use dynamic allocation??

  int evencount =0;
  int oddcount =0;
  int *evenarray = malloc(sizeof(evenarray)); //not sure if this is setup correctly
  int *oddarray = malloc(sizeof(oddarray)); //not sure if this is setup correctly
  for(i=0;i<n;i++)
  {
    if(array[i] % 2 == 0) //if value in array CAN be divided by 2
    {
      printf("Printing to even array.\n");
      evenarray[evencount] = array[i];
      evencount++;
    }
    else //if this is not true, append to odd array
    {
      printf("Printing to odd array.\n");
      oddarray[oddcount] = array[i];
      oddcount++;
    }
  }

  printf("evenarray = ");
  for(i=0;i<evencount;i++){
    printf("%d, ", evenarray[i]);
  }
  printf("\n");
  printf("oddarray = ");
  for(i=0;i<oddcount;i++){
    printf("%d, ", oddarray[i]);
  }
  printf("\n");

这里的注释“int *evenarray = malloc(sizeof(evenarray)); //not sure if this is setup correctly”是准确的。它们没有被正确地分配。 - Simon F

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接