简体   繁体   中英

Recursion calling function with ampersand

How should I interpet the code below? The &arr[1] threw me of completely. I just started to think that I was getting recursion. Say n = 7 . Then it will first print out arr[6] then printArray(6, &arr[1]) , printf ("%d", arr[6-1]) .
And it will repeat as long as n>0 .

But how does the address of the second element play into this recursion.

void printArray(int n, int arr[]){

    if(n>0){
          printf("%d", arr[0]);
          printArray(n-1, &arr[1]);
    }

}

The version you posted will just keep printing the last element each time around, since on each resursive call it (a) decreases the count and (b) adjusts arr to point to the next element in the array.

Here's a version that will print the entire array, in order:

void printArray(int n, int arr[])
{
    if (n > 0) {
        printf("%d", arr[0]);
        printArray(n-1, &arr[1]);
    }
}

Alternatively, you could recurse first:

void printArray(int n, int arr[])
{
    if (n > 0) {
        printArray(n-1, arr);
        printf("%d", arr[n-1]);
    }
}

I used the same format specifier that you had in your example, but note that there is no separation between one element and the next with this format. You might want to add a space or newline to the end.

Arrays in C are just pointers. &arr[1] is the pointer to the second item in the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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