c-代码不会在一维数组中检查多个重复的整数

  • 本文关键字:整数 代码 一维数组 c arrays
  • 更新时间 :
  • 英文 :


我编译了一段代码来检查一维数组中的重复项,唯一的问题是它会显示一个重复项,但不会显示其他重复项。我已经包含了我的代码。我是一个新手,我很难走到这一步。

这是我的代码:

#include <stdio.h>
#include <malloc.h>
void duplicate(int array[], int num)
{
    int *count = (int *)calloc(sizeof(int), (num - 2));
    int i;
    printf(" The duplicate integers in this array are: ");
    for (i = 0; i < num; i++)
    {
        if (count[array[i]] == 1)
            printf(" %d ", array[i]);
        else
            count[array[i]]++;
    }
}
int main()
{
    int array[] = {7, 77, 42, 2, 1, 4, 2, 7, 42};
    int array_freq = sizeof(array) / sizeof(array[0]);
    duplicate(array, array_freq);
    getchar();

    return 0;
}

您在count数组中的方式越界,执行count[array[i]]将意味着您使用e、g、array[1]作为count数组中的索引,而array[1]77,意味着您使用77作为只有7个条目的count的索引。

这当然会导致未定义的行为

除了@JoachimPileborg在回答中指出的关于越界访问count的问题之外,我认为您没有正确的逻辑来检查重复项。

让我们从array的第一个元素7开始。

检查以后是否找到7。找到后,打印重复项。

然后请注意,您已经检查了7的重复项。当您在array上迭代时遇到7时,您不必再次检查7的重复项。

void duplicate(int array[], int num)
{
   int i;
   int j;
   int* status = calloc(sizeof(int), num);
   printf(" The duplicate integers in this array are: ");
   for (i = 0; i < num; i++)
   {
      if ( status[i] == 1 )
      {
         // Already visited and marked as duplicate
         // Go on to the next item.
         continue;
      }
      for ( j = i+1; j < num; ++j )
      {
         if (array[i] == array[j])
         {
            // Note that array[j] has already been visited and
            // marked as a duplicate.
            status[j] = 1;
            // If array[i] is not already printed, print it and
            // mark it as a duplicate.
            if ( status[i] == 0 )
            {
               printf(" %d ", array[i]);
               status[i] = 1;
            }
         }
      }
   }
   printf("n");
   // Make sure to deallocate the memory before returning from
   // the function.
   free(status);
}

最新更新