0

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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Hmm, that didn't do the trick. Now I get a write access violation when the program gets to the first scanf
@AlexSorkin See Jay Kumar R's answer.
1

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 & .

1 Comment

Alex , it may have helped you, but to understand you have to read more and understand and take baby steps. good luck.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.