c - C 中的函数没有返回正确的值

标签 c

我试图在不使用循环的情况下检查数组是否已排序。它工作正常,即。如果我有一个包含按升序排列的元素的数组,则 printf 会执行,因为我得到“已排序”。但是

printf("数组 1 返回:%d\n\n", sortCheck(arr1, SORTED1));

返回 0?为什么是这样?

谢谢。这是完整的代码。

#include<stdio.h>

const int SORTED1 = 5;

int sortCheck (int arr[], int arrSize);

int indexCounter = 0;

int main()
{
    int arr1[] = {1,2,3,4,5};

    printf("Array 1: \n");
    printf("Array 1 returns: %d \n\n", sortCheck(arr1, SORTED1)); 


    indexCounter = 0; 
    return 0;
}

int sortCheck(int arr[], int arrSize)
{   
    if ( (arr[indexCounter]==arr[arrSize-1]) && (indexCounter==arrSize-1) )
    {
        printf("Sorted. \n");
        return 1;
    }
    if ( arr[indexCounter] <= arr[indexCounter+1] )
    {
        indexCounter++;
        sortCheck(arr, arrSize);
    }
    else
    {
        printf("Not sorted.");
        return 0;
    }   
}

最佳答案

由于缺少 return 语句,您看到了未定义的行为。

if ( arr[indexCounter] <= arr[indexCounter+1] )
{
    indexCounter++;

    // Problem. Missing return.
    sortCheck(arr, arrSize);
}

将违规行更改为:

    return sortCheck(arr, arrSize);

关于c - C 中的函数没有返回正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28978153/

相关文章:

c - c中链表期间的段错误

java - 将 Java float 转换为 C

c - 有没有办法限制用户只能输入变量的数值?

c - 对文件 C 中的行进行排序

c - UNIX 先进先出 : the process hangs if I don't close the input side of the fifo

创建一个 "template"(格式)字符串

c - 两个循环之间哪个最好?

c - 小写字母转大写(如果条件使用)?

c - 为什么readlines函数要使用alloc?

c++ - 您如何在托管代码环境之外安全地进行编程?