Structure as a function of parameters
- The entire structure can be passed as a parameter to the function
- In this case, a new struct variable is created in the function, and the value of the call to this structure is copied (focus, just pass the value into the function, and the real variable outside the function does not change, unlike the array)
- Function can also return a structure
Let's go straight to a simple example:
issue: the user enters today's date and outputs tomorrow's date.
Hint: Leap year, last day of the month,
Code:
#include <stdio.h>
#include <stdbool.h>
/* Calculate tomorrow's date based on today's date. */
The struct is placed on the outside of the function, which is equivalent to a global variable, and all functions can be used.
struct date
{
int month;
int day;
int year;
}; Remember this semicolon.
BOOL Is_leap (struct date D); Determine if a leap year
int numbersofdays (struct date D); Give the number of days of the month
int main (int argc, char const *argv[])
{
struct date today; Define two struct-body variables
struct date tomorrow;
int days;
int flag=1; Implementing input Control
printf ("Please enter today's date (9-24-2012):");
scanf ("%i-%i-%i", &today.month,&today.day,&today.year);
Days = Numbersofdays (today);
Tomorrow = Today; Can be assigned the same value as a general variable
if (today.day<days && today.month <=12) {
Tomorrow.day = Today.day + 1;
}else if (today.day = = Days && today.month <12) {
Tomorrow.day = 1;
Tomorrow.month +=1;
}else if (today.day = = Days && Today.month = = 12) {
Tomorrow.day = 1;
Tomorrow.month = 1;
Tomorrow.year+=1;
}else{
Flag = 0;
printf ("Wrong input!") ");
}
if (flag) {
printf ("Tomorrow's date is:");
printf ("%i-%i-%i\n", tomorrow.month,tomorrow.day,tomorrow.year);
}
return 0;
}
BOOL Is_leap (struct date D)
{
BOOL is = false;
if ((d.year%4==0 && d.year%100!=0) | | d.year%400==0)
is = true;
return is;
}
int numbersofdays (struct date D)
{
int days;
int dayspermonth[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
if (d.month==2 && is_leap (d))
{
days = 29;
}
Else
{
days = Dayspermonth[d.month-1];
}
return days;
}
C language----Structure---structure and function