我试图修改 K&R 的 C 书中的 month_day
程序。以下代码是K&R的month_day
函数(第111页,第5.7节)
void month_day(int year, int yearday, int *pmonth, int *pday){...}
如果在main()
中调用:
int main()
{
int month = 0, day = 0;
month_day(1996, 290, &month, &day);
}
然后 month
是 10,day
是 16。所以没关系。但我想让月份是一个字符串,我需要 month
为“OCT”。
所以我声明了一个月份名称的指针数组,
char *monthnames[0] = {
"Illegal Month",
"JAN", "FEB", "MAR",
"APR", "MAY", "JUN",
"JUL", "AUG", "SEP",
"OCT", "NOV", "DEC",
}; // "Illegal Month" is there to adjust index numbers to months. So "JAN"
// is monthnames[1] (It'll be monthnames[0] otherwise).
然后我更改month_day
,
char daytab[2][13] = {
{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};
void month_day(int year, int yearday, char *pmonth, int *pday)
{
int leap, i;
char *p;
leap = (year % 4) == 0 && (year % 100) != 0 || (year % 400) == 0;
p = &daytab[leap][1];
for (i = 1; yearday >= *p; i++) {
yearday -= *p;
p++;
}
*pday = yearday;
pmonth = monthnames[i]; // I expect pmonth to be pointed to i-th String in monthnames[].
}
在 main()
中:
int main()
{
char *month;
int day;
month_day(1996, 290, month, &day); // I expect month is pointed to "OCT" & day is 16.
printf("1996-%s-%d", month, day);
}
我可以毫无错误地编译它。 但是当我运行它时,它会在 Windows 中显示“.exe 已停止工作”错误。 有人可以解释一下为什么吗? 并告诉我该怎么做?
最佳答案
您正在通过传递指向 day
的指针来模拟按引用传递,您也需要为 month
做同样的事情,即传递指向指针的指针。
关于c - 在 C 中,将字符指针传递给函数并使其指向某处,这是错误的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33251386/