Expression must have a class type

So I have this simple header file and when I was creating sum of the functions to be contained in it. I have an error that repeats whenever I access the array x[]. Wherever I try to access the array it says that the expression must have a class type. I am completely lost on a fix for it.

useful.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#pragma once
#include <array>

double avg(int x[])
{
	int sum = 0;
	for (int i = 0; i < x.size(); i++)
		sum += x[i];
	return sum / x.size();
}

double avg(float x[])
{
	double sum = 0;
	for (int i = 0; i < x.size(); i++)
		sum += x[i];
	return sum / x.size();
}

Thanks in advance for any advice given.
Last edited on
Hi,
If you are using array header file you have to use <> stuff (IDK what those notion are called, vector is it?)

http://en.cppreference.com/w/cpp/header/array
http://en.cppreference.com/w/cpp/container/array/tuple_size
An int or float array doesn't have a method size().
For normal arrays, you must have an additional "size" parameter for each your function :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
double avg(int x[], int size)
{
	int sum = 0;
	for (int i = 0; i < size; i++)
		sum += x[i];
	return sum / size;
}
double avg(float x[], int size)
{
	double sum = 0;
	for (int i = 0; i < size; i++)
		sum += x[i];
	return sum / size;
}
Last edited on
And for example, in the function main(), you call it :
1
2
3
4
5
float arr_f[] = {11.5, 18.6, 9.2, 8.4, 6.0};
int arr_i[] = {15, 16, 2, 8, 6};

cout << avg(arr_f, 5);
cout << avg(arr_i, 5);
Last edited on
Does that help? :)
For normal arrays, you must have an additional "size" parameter for each your function :

That solution works well thank you.
Glad it helped :)
Topic archived. No new replies allowed.