c - 执行排序和搜索 C 函数时出错

标签 c arrays sorting

我定义了两个函数searchsort,它们在另一个程序中使用。当我尝试运行该程序时,出现错误意外输入。错误是什么意思?我不知道我的代码有什么问题。

#include "helpers.h"

/**
 * Returns true if value is in array of n values, else false.
 */

      bool search(int value, int values[], int n)
      {
        values[n] = n;
        for(int i=0; i < n; i++)
        {
          if(values[n] == value && value > 0)
            return 0;
          else
            return 1;
        }
        return 0;
     }

/**
 * Sorts array of n values.
 */


    void sort(int values[], int n)
    {
      int min, swap;
      for(int i=1; i < (n-1); i++)
      {
        min = i;
        for(int j=i+1; j< n; j++)
        {
          if(values[j] < values[min])
              min = j;
        } 
        if(min != i)
        {
          swap = values[i];
          values[i] = values[min];
          values[min] = swap;
        }
      }
      return;
    }

这是我将调用上述两个函数的主程序

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

       #include "helpers.h"

      // maximum amount of hay

       const int MAX = 65536;

      int main(int argc, string argv[])
         {
   // ensure proper usage

            if (argc != 2)
          {
           printf("Usage: ./find needle\n");
           return -1;
           }

     // remember needle

          int needle = atoi(argv[1]);

         // fill haystack
           int size;
           int haystack[MAX];
           for (size = 0; size < MAX; size++)
             {
                // wait for hay until EOF

                 printf("\nhaystack[%d] = ", size);
                  int straw = GetInt();
                    if (straw == INT_MAX)
                    {
                          break;
                     }

                   // add hay to stack

                 haystack[size] = straw;
             }
             printf("\n");

        // sort the haystack

         sort(haystack, size);

     // try to find needle in haystack

          if (search(needle, haystack, size))
            {
             printf("\nFound needle in haystack!\n\n");
             return 0;
            }
            else
           {
               printf("\nDidn't find needle in haystack.\n\n");
               return 1;
           }
        }

最佳答案

如果这不会导致错误,那么它肯定会导致错误。在您的搜索函数中,您有一个大小为 n 的数组和访问索引 n,尽管最大索引为 n-1。 此外,搜索中的循环将始终立即退出,而不实际检查任何内容。我强烈建议您单步执行代码的每一行,并用变量中的值替换以查看会发生什么。

关于c - 执行排序和搜索 C 函数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25074063/

相关文章:

perl - 当键是动态的时在Perl中对哈希排序

c - netfilter转发钩子(Hook)点修改数据包

Java Applet - ArrayIndexOutOfBoundsException(第 2 部分)

java - 如何使用 Java ByteBuffer 处理负 int

java - 分配一个数组需要多长时间(在 Java 中)

java - 使用 IgnoreCase 按键对 Map<String, Object> 进行排序?

java - 求某些条件下归并排序的时间复杂度

python - 从C向Python程序发送字符串

c - 嵌入式系统上的外部文件资源(C语言加FAT)

c - 使用 malloc (C89) 在 main() 之外初始化结构