Reputation: 43
Assignment requires using a function to input data into a struct
typedef struct AC {
char code[4];
double cost;
unsigned day;
} AC;
My function so far is
int main(){
AC *ac;
input(&ac);
}
void input(AC * ac)
{
printf_s("Input code (3 characters), cost, and day (0 = Sun 6 = Sat) separated by spaces: \n");
gets(ac->code);
printf_s("\nCode: %s\n", ac->code);
scanf_s(" %lf", ac->cost);
printf_s("\nCost: %.2lf\n", ac->cost);
scanf_s(" %i", ac->day);
printf_s("\nDay: %i\n", ac->day);
}
The gets for the airport code works fine, but the scanf for cost and day don't seem to do anything; using breakpoints, it seems like the function isn't placing the values scanf gets into the struct. Instead, cost just remains garbage code after that part is done.
Don't worry about error checking or anything, I'm just interested in how to make the function properly take the input values and put them in the struct.
Upvotes: 0
Views: 1020
Reputation: 537
use & .
Like scanf_s(" %i", &ac->day)
;
A string is character array ( char * or char [] ) So it does not require &. But non-arrays require it.
Also you should declare AC ac;
(as Michael Arbers pointed out first) then pass the address ( &ac)
when calling the function call. That is because you are passing address and declared the function to take pointer to AC (AC *ac).
In C language, when you declare an address variable (pointer) you use * . When fetching the address you use & .
Upvotes: 1
Reputation: 3779
You've got undefined behavior all over. The problem is that there is no actual space for the AC
struct you're populating. It's a simple change. Replace AC *ac;
with AC ac;
. That changes ac
from a pointer to an actual struct with backing memory.
Upvotes: 2