是否可以使用指针(空指针?)遍历可变参数函数的参数到最后命名的参数?(我知道这不是使用可变参数的正确方法,但我仍然对它是否可行感兴趣)
将指针设置到字符串的末尾不起作用,因为在我开始移动指针后,它指向程序中使用的其他字符串。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void form_date(MON* datePtr, int dayMonth, int dayYear, int month);
MON* evaluate_date(MON* datePtr, int count, int dayArg);
void what_month(char *format, ...);
void output(MON* datePtr, int count);
int main(void)
{
what_month("ii", 126, 125);
return 0;
}
void what_month(char *format, ...){
char* arg_ptr = format+2;
int* arg_int_ptr;
double* arg_double_ptr;
MON dateArr[MAX_DATE];
int count = 0;
int dayYear;
char *ptrFormat = format;
for(; *ptrFormat != '\0'; ptrFormat++){
if(*ptrFormat == 'i'){
arg_int_ptr = (int*) arg_ptr;
dayYear = *arg_int_ptr;
arg_int_ptr++;
}
if(*ptrFormat == 'd'){
arg_double_ptr = (double*) arg_ptr;
dayYear = *arg_double_ptr;
arg_int_ptr++;
}
evaluate_date(dateArr, count, dayYear);
count++;
}
output(dateArr, count);
}
void form_date(MON* datePtr, int dayYear, int dayMonth, int month){
char month_names[][15] = {"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November",
"December", "INVALID_MONTH"};
datePtr->day_of_year = dayYear;
datePtr->day_of_month = dayMonth;
if(month == -1){
strcpy(datePtr->month, month_names[12]);
}
else {
strcpy(datePtr->month, month_names[month]);
}
}
MON* evaluate_date(MON* dateArr, int count, int dayArg){
int months_days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int j;
int dayMonth;
int sumDays = 0;
if (dayArg > 365 || dayArg < 1){
form_date(dateArr + count, dayArg, -1, -1);
count++;
}
else {
for(j = 0; j < 12; j++){
sumDays += months_days[j];
if (dayArg <= sumDays)
break;
}
dayMonth = months_days[j] - (sumDays - dayArg);
sumDays = 0;
if (dayMonth == 0){
dayMonth++;
}
form_date(dateArr + count, dayArg, dayMonth, j);
}
return dateArr;
}
void output(MON* dateArr, int count){
int i, j;
for(i = 0; i < 80; i++)
printf("_");
printf("\n");
for(i = 0; i < 80; i++)
printf("_");
for(j = 0; j < count; j++){
if (j % 100 == 0 && j != 0){
puts("Press any key to continue");
getchar();
}
printf("\n%-7d ::: %7d, %-8s %5s\n", dateArr[j].day_of_year, dateArr[j].day_of_month,
dateArr[j].month, "|");
}
for(i = 0; i < 80; i++)
printf("_");
}