A normal variable sum
is treated as one-element array for pointer aritimetic (N3337 5.7 Additive operators) and when ptr
points at it, ptr+1
doesn't point at a valid object and therefore must not be dereferenced.
If you want continuous memory region, use arrays.
Also note that
- Checking
!cin.eof()
after updating sum
and average
doesn't seem a good idea because it will use an invalid (duplicate) data. Check if input is successful before processing the data.
- Declareing
void main()
(or main
with return type other than int
) in the global namespace is illegal in the standard C++. Unless you have some special reason -- for example, your boss or teacher forbids writing standard-compliant code -- you should use int main()
(in this case).
- You should initialize
counter
to 1
to put inputVal
in the number. Avoiding getting input as argument to avoid writing duplicate code seems better.
Try this:
#include <iostream>
using std::cin;
using std::cout;
template <class type > type* calculate(type inputVal) {
type val;
static int counter = 1;
static type buffer[2];
type& sum=buffer[0];
type& average=buffer[1];
sum=average=inputVal;
static type* address = buffer;
for(;;) {
cout << "Enter value: ";
if(!(cin >> val)) break;
counter++;
sum += val;
average = sum / counter;
}
return address;
}
int main() {
int num;
cout << "Enter Value: ";
cin >> num;
int *ptr = calculate(num);
cout << "SUM: " << *ptr << " AVG: " << *(ptr+1);
}
Or this without input from the argument:
#include <iostream>
using std::cin;
using std::cout;
template <class type > type* calculate() {
type val;
static int counter = 0;
static type buffer[2];
type& sum=buffer[0];
type& average=buffer[1];
sum=0; // the type used has to be capable to be converted from integer 0
average = 0;
static type* address = buffer;
for(;;) {
cout << "Enter value: ";
if(!(cin >> val)) break;
counter++;
sum += val;
average = sum / counter;
}
return address;
}
int main() {
int *ptr = calculate<int>();
cout << "SUM: " << *ptr << " AVG: " << *(ptr+1);
}