简体   繁体   English

使用C中的递归打印整数数组的逆序

[英]printing the reverse of an integer array using recursion in C

I am not able to understand how I am getting a garbage value in output . 我无法理解我如何在输出中获得垃圾值。 Can someone explain me the flow . 有人可以向我解释一下流程。 Thank you . 谢谢 。

#include <stdio.h>

void rev(int *ptr){

  if(*ptr) {
    rev(ptr+1);
    printf("%d\n",*ptr);

  }
}

int main(){      

  int arr[]={4,2,3,1,5};  
  rev(arr);  
  return 0;  
}

output - 输出-

32764   
5
1
3 
2  
4     

Your relying on if (*ptr) being 0 to block the recursion is not going to end well. 您依靠if (*ptr)为0来阻止递归不会很好地结束。 Arrays in C are not terminated with zero automatically. C中的数组不会自动以零终止。 Formally, the behaviour of your program is undefined as you will attempt to read memory past the end of the array. 形式上,程序的行为是不确定的,因为您将尝试读取数组末尾的内存。

The normal way of dealing with this is to either pass the array length, or use a special value to signal the end of the array. 解决此问题的通常方法是传递数组长度,或使用特殊值来表示数组结尾。

Your base condition is not correct. 您的基本条件不正确。 You recurse until a 0 is found in the array but it doesn't have one. 您递归直到在数组中找到0,但没有1。

You have perhaps (incorrectly) assumed that there's a 0 after the end of the array. 您可能(不正确地)假定数组结尾之后为0。 But this is not true in C. Your program has undefined behaviour as per C standard. 但这在C语言中是不正确的。根据C标准,您的程序具有未定义的行为

If you need to print the entire array, then pass the size as well: 如果您需要打印整个数组,请同时传递大小:

void rev(int *ptr, size_t size){    
    if(size) {
        rev(ptr+1, --size);
        printf("%d\n",*ptr);
    }
}

int main(){

    int arr[]={4,2,3,1,5};
    rev(arr, sizeof arr/sizeof arr[0]);
    return 0;
}

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

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