Re: question about arrays, structures, functions
* Art Cummings:
Good morning all. I just finished an assignment using structures. In this
assignment I used an array of structures. What I would have liked was to
use an array of structures with a function. The problem I ran into, was
when the i tried to read the data in the structure I got garbage. Normally
when I use arrays they retain the information that I enter once the function
completes. I'm thinking that it has something to do with using the
structure within the function. I was able to create the function prototype,
the function call and the function header, but I wasn't able to get any data
populated in my structures. I've include the prototype, function call and
header. Any help with understanding if and how this is possible would be
appreciated. The program I created uses an array of structures but does not
call it in a fuction so I got around having to retain the data after the
function ended.
Thanks Art
struct WeatherStats
{
float rainFall; //total rainfall by month
float highTemp; //high temp for month
float lowTemp; //low temp for month
float avgTemp; //avg temp for month
};
//function prototype for data getData
void getData(WeatherStats[], int);
//currentYear is type WeatherStatas
getData(currentYear, NUM_MONTHS); //function call to getData
Here you're saying the first argument is an array of stats for the
current year, and the second arg is the number of months in the year (or
elements in the array). But
//function header
void getData(WeatherStats currentMonth[], int theMonth)
here you're saying the first argument is the stats for a single month,
and the second argument is the month number.
So what is it?
Since I can't make heads or tails of your example (see comments above)
I'll just give you an example of filling an array with data, C style:
struct Datum
{
int x, y;
};
Datum datum( int x, int y ) { Datum d = {x, y}; return d; }
void getComputedData( Datum data[], int size )
{
for( int i = 0; i < size; ++i )
{
data[i] = datum( i, -i );
}
}
int main()
{
Datum data[5];
getComputedData( data, 5 );
// Use data here.
}
Doing the same C++ style:
#include <vector>
struct Datum
{
int x, y;
Datum( int x_, y_ ): x( x_ ), y( y_ ) {}
};
typedef std::vector<Datum> Data;
Data computedData( int size )
{
Data result;
for( int i = 0; i < size; ++i )
{
result.push_back( Datum( i, -i ) );
}
return result;
}
int main()
{
Data data = computedData();
// Use data here.
}
Cheers, & hth.,
- Alf
PS: It's a good idea to not use all uppercase names except for macros.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?