#include <iostream>
using std::cout;
using std::endl;
void someFunction (int[], int);
int main()
{
constint arraySize = 10;
int a[arraySize] = {32, 27, 64, 18, 95, 14, 90, 70, 60, 37};
cout << "The values in the array are: " << endl;
someFunction (a, arraySize);
cout << endl;
return 0;
}
void someFunction (int b[], int size)
{
if (size > 0){
someFunction (&b[1], size - 1);
cout << b[0] << " ";
}
}
You're supposed to identify what this program does (the answer is shortly given afterwards though), so, it prints the whole array given backwards, which means 37, 60, 70, 90, 14, 95, 18, 64, 27, 32. Can someone explain to me what is happening in this function (besides that it loops itself)?
Since an array is a contiguous storage space in memory, you can continue this pointer arithemetic until you get to the end of the array. And to get the first item, you simply print *ptr or ptr[0]
Here is the code rewritten, using different format:
Thank you for explaining Smac89, I had a friend explain to me detailed what happens throughout every function call and I got it but I didn't know that pointers can work that way too. I'll write here what I learned for archive purposes:
The first time this function gets called from main, its parameters start with the whole array a (giving a as parameter means you give the address of the array's first element a[0]) and the full size of the array (10).
In first function call, if is true so the function gets called again but now its parameters are b[1] (which means it points to the address of the array's second element a[1], so essentialy the array given is a sub-array from the original array starting from its second element) and one less size (9).
In next function call, if is also true so the function gets called again and now it's parameters are again b[1] (this time though it points to the adress of the sub-array's second element which is essentialy a[2]) and one less size (8).
This concept continues until size is 0 , so if is false and the last function call exits without doing anything. Then we return to its previous function call. The sub-array given here should have only one element, the original array's last element a[9], so when cout prints the sub-array's first element b[0], it actually prints a[9].
Function exits and we return to the previous function call. The sub-array given here should be the original array's last 2 elements a[8] and a[9]. So now, when cout prints the sub-array's first element b[0] it actually prints the original array's 2nd from last element a[8].
This concept continues until every function call is finished and the program returns to main.