AuSm88 AuSm88 - 2 months ago 13
C Question

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

usr usr
Answer

Your base condition is not correct. You recurse until a 0 is found in the array but it doesn't have one.

You have perhaps (incorrectly) assumed that there's a 0 after the end of the array. But this is not true in C. Your program has undefined behaviour as per C standard.

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