简体   繁体   English

C中的函数未返回正确的值

[英]Function in C not returning proper value

I'm trying to check whether an array is sorted without using a loop. 我正在尝试检查是否在不使用循环的情况下对数组进行了排序。 It's working properly, i,e. 即工作正常。 if I have an array with elements that are in ascending order, the printf executes, since I get "Sorted." 如果我有一个包含按升序排列的元素的数组,则将执行printf,因为我得到了“已排序”。 But

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

returns 0? 返回0? Why is this? 为什么是这样?

Thanks. 谢谢。 Here's the entire code. 这是完整的代码。

#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;
    }   
}

You are seeing undefined behavior due to a missing return statement. 由于缺少return语句,您看到未定义的行为。

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

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

Change the offending line to: 将有问题的行更改为:

    return sortCheck(arr, arrSize);

Following changes should print value 1 以下更改应打印值1

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

the sortCheck() function does not check if the array is sorted. sortCheck()函数不检查数组是否已排序。

there are two reasons for this. 有两个原因。

1) when the recursive call was invoked, the returned value is being ignored, so the information about a particular byte pair is lost. 1)调用递归调用时,返回值将被忽略,因此有关特定字节对的信息将会丢失。

2) the index (arrSize) is always passed, rather than the offset to the current byte index 2)总是传递索引(arrSize),而不是当前字节索引的偏移量

IE the whole sortCheck() function needs to be re-designed. IE浏览器的整个sortCheck()函数需要重新设计。

Using a debugger (or a printf( of the parameters) in the path that calls the recursive sortCheck() would have revealed that fact. 在调用递归sortCheck()的路径中使用调试器(或参数的printf())将揭示这一事实。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM