Hi,
I am going through the book "C++ primer" doing all the exercises. Exercise 5 chapter 8 says to write a template function max5() that takes as its argument an array of five items of type T and returns the largest item in the array. My code compiles but does not run, I don't understand why. I use Xcode on a Mac.
Thank you very much
[code]
#include <iostream>
template <typename T>
T max5(T * arr);
int main(int argc, const char * argv[])
{
using namespace std;
int arr[5] = {9,48,6,22,7};
int result = max5(arr);
cout << result << endl;
return 0;
}
template <typename T>
T max5(T arr[]){
T result = arr[0];
for (int i = 1; i < 5; ++i)
{
if (arr[i] > result)
{
result = arr[i];
}
}
return result;
}
The program ran fine for me on an online compiler, so maybe there's something wrong with your Xcode project. I've never used Xcode so I can't really help you there.
I found what the problem is, this is ridiculous. Sometimes it is good to stop working when one is tired and try again in the morning.
So the problem is that I keep adding breakpoints to my program without noticing...so there was a breakpoint in the middle of it, and that is why the program stopped. I removed it, and it is working fine now.
Kesiverto, according to the book, T * arr and T arr[] are equivalent as formal parameters in the function prototype and the function definition. They both are a pointer to T and correspond to the same signature.