Can't find error in a structure initilization

I am writing a program that asks the user to enter the expenses for each
season of the year, and then sum the expenses. The thing is, I have to do it by passing a structure with single array to the functions. I don't know why but for some reason I got error like this : error C4700: uninitialized local variable 'year' used.
I think that I've declared everything well.
I am using Visual Studio 2013, here is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
  #include <iostream>
using namespace std;

// constant data
const int Seasons = 4;
const char *Snames[4] = { "Spring", "Summer", "Fall", "Winter" };
struct expenses
{
	double tab[Seasons];
};
// function to modify array object
void fill(expenses str,int n);
// function that uses array object without modifying it
void show(expenses str,int n);

int main()
{
	expenses year;

	fill(year,Seasons);
	show(year,Seasons);
	return 0;
}
void fill(expenses str, int n)
{
	
	for (int i = 0; i < n; i++)
	{
		cout << "Enter " << Snames[i] << " expenses: ";
		cin >> str.tab[i];
	}
}
void show(expenses str, int n)
{
	
	double total = 0.0;
	cout << "\nEXPENSES\n";
	for (int i = 0; i < Seasons; i++)
	{
		cout << Snames[i] << ": $" << str.tab[i] << endl;
		total += str.tab[i];
	}
	cout << "Total Expenses: $" << total << endl;
}
Read what @AbstractionAnon said below me. You can pass it by reference by adding & after expenses.

void show(expenses& str, int n)
Last edited on
Line 24: You're passing expenses by value, but the object has not been initialized yet. The intent of your function is to fill in expenses, so you want to pass expenses by reference, not value. You want to operate on the call's struct, not a local copy that goes out of scope when fill exits.

You are passing a copy of an uninitialized variable to a function. The only reason to do that is if the function is going to use the values contained in the variable. It wouldn't make sense to pass a variable by value if you were going to modify it. So, your compiler is letting you know something is off (and it is -- fill should take its first argument by reference.)
Last edited on
Thank you, now it works fine, but I don't get why can I pass an array without errors like that?
Is it because I am not really passing an array value to the function but the address of its first element? What if I tried to pass just the array from my structure by value? Should it work fine then? Your comments were really helpful so far.
Topic archived. No new replies allowed.