What is the reason for error while returning a structure in this C program?

前端 未结 5 1491
粉色の甜心
粉色の甜心 2020-12-21 14:54

My program intends to achieve this

(A) Write a C function named larger() that returns the later date of any two dates passed to it. For

5条回答
  •  温柔的废话
    2020-12-21 15:29

    DATES result[NUM] = larger(DATES user[NUM]);
    

    What's this intended to do? DATES result[NUM] declares an array of DATES. (But each DATES contains only one date, which is confusing.) But despite being an array, it's initialized with a single object, the return value from larger. The argument to larger, DATES user[NUM], appears to be declaring user, a variable which already exists. It looks like you're trying to clarify to the compiler that user is an array of dates, but DATES doesn't go there and [NUM] appears to be indexing into the array, which you don't want.

    Probably what you want is

    DATES result = larger( user );
    

    Also there are some serious style issues which will cause trouble later:

    • Array types for function parameters as in DATES larger(DATES[NUM]); are converted to pointers. On that line, NUM does nothing and the declaration is the same as DATES larger( DATES * );. Despite what some teachers may say, pointers and arrays are not the same thing. When the distinction is important, this style causes confusion. Use DATES larger( DATES * ) instead.

    • It doesn't make sense to capitalize DATES. Caps usually indicate a preprocessor macro.

    • Preprocessor macros are like a sledgehammer. Using them for simple numeric constants is less elegant than constructs like const int num = 2; or enum { num = 2 };

    • Descriptive variable names like input_limit and user_input would be better than num and user.

    • Don't rely on uninitialized data. user[0].month might be 6 after user is defined but not initialized. Always write a value before reading.

    • Braces should be kept visible. Grouping braces closely with the first and last words of the loop hides them, which is good if you think they're ugly, but then it's very very easy to incorrectly add a line to the loop, producing a hard-to-debug flow control error.

提交回复
热议问题