There is no way to directly return an array in C. The quick explanation is arrays aren't "first class citizens" in C, meaning you can't treat them like "normal" variables, such as a single int, double, char, etc. When you return an array that is local to a function you are actually returning a pointer to the beginning of the array. Since the function is done, all it's local variables cease to exist, so your pointer doesn't actually point to the array anymore, just to where it was. The data there is unreliable, accessing it is undefined. In general, for "returning" arrays in C you have a few options:
- Declare an array in main, and pass it into your input() function.
- Have input() return a pointer to a double (double *), and allocate memory for the array inside input(), via malloc/calloc. Pass back the pointer to that allocated memory.
- Declare fahr to be static. That means that the array is local (only visible within the function), but it's storage duration (a.k.a. lifespan) is the whole time the program is running. This means the pointer you return is valid after the function is done.
For your situation, however, you only have one good option, #1. The second option is no good because you don't want to keep allocating a new array every time you call the function and it's hard to keep track of whether you already allocated memory for the array. The third option would work for a simple program like this (you only need to put the word 'static' at the beginning of the declaration of 'fahr'), it's just not as ideal as #1.
Also, it's a good idea to #define some constants instead of using magic numbers.
Code:
#define NUM_TEMPS 25
#define MAX_TEMP 175.0
// void here isn't necessary, but I like to be specific
int main(void)
{
double fahr[NUM_TEMPS];
input(fahr); // call input() and pass it the array to store data in
return 0;
}
// void here means return nothing -- we pass in the array to fill, so no need to return anything
void input(double fahr[])
{
...
if (My_temp < 0 || My_temp > NUM_TEMPS)
...
if (fahr[My_temp] < -MAX_TEMP
}
I think you get the idea.