我有这样的程序
#include <stdio.h>
#include <conio.h>
typedef struct {
const char* dotw;
int dd,mm,yyyy;
} date;
void indate(date *a);
void outdate(date a);
int datecmp(date a, date b);
int leapyear(int yyyy);
const char* dotw(date a);
date datecal(date a,int n);
int main()
{
while (1) {
date a;
indate(&a);
printf(dotw(a));
}
getch();
}
//print date on screen
void outdate(date a)
{
printf("\nDay %d Month %d Year %d",a.dd,a.mm,a.yyyy);
}
//compare beetween two date
int datecmp(date a, date b)
{
if (a.yyyy<b.yyyy||(a.yyyy==b.yyyy&&a.mm<b.mm)||(a.yyyy==b.yyyy&&a.mm==b.mm&&a.dd<b.dd)) return -1;
else if (a.yyyy==b.yyyy&&a.mm==b.mm&&a.dd==b.dd) return 0;
return 1;
}
//enter date
void indate(date *a)
{
int tmp;
printf("\nEnter Day: ");
scanf("%d",&tmp);
(*a).dd=tmp;
printf(" Month: ");
scanf("%d",&tmp);
(*a).mm=tmp;
printf(" Year: ");
scanf("%d",&tmp);
(*a).yyyy=tmp;
}
//Check for leap year
int leapyear(int yyyy)
{
if (yyyy%4!=0||(yyyy%100==0&&yyyy%400!=0)) return 0;
return 1;
}
//day of the week
const char* dotw(date a)
{
int i=0;
const char* dayotw[]={"SaturDay","SunDay","MonDay","TuesDay","WednesDay","ThursDay","FriDay","SaturDay"};
static date mark={"SaturDay",2,8,2014};
if (datecmp(a,mark)==-1)
{
while (datecmp(datecal(a,i),mark) != 0) i++;
return(dayotw[7-i%7]);
}
else
{
while (datecmp(datecal(mark,i),a) != 0) i++;
return (dayotw[i%7]);
}
}
//Which day is after n day of date a
date datecal(date a,int n)
{
int i;
static int Month1[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
static int Month2[]={0,31,29,31,30,31,30,31,31,30,31,30,31};
for (i=0;i<n;i++)
{
if ((a.dd+1>Month1[a.mm]&&!leapyear(a.yyyy))||(a.dd+1>Month2[a.mm]&&leapyear(a.yyyy)))
{
if (a.mm+1>12)
{
a.yyyy+=1;
a.mm=a.dd=1;
}
else
{
a.mm+=1;
a.dd=1;
}
}
else a.dd+=1;
}
a.dotw=dotw(a); **//if i insert this line, program will error while running program**
return a;
}
在a.dotw=dotw(a)
处查看代码的结尾。如果我插入该行,程序将在运行时出错。但为什么会出错?
答案 0 :(得分:1)
如果使用调试器运行代码,您将看到违规行是:
Process 89597 stopped
* thread #1: tid = 0x4598795, 0x0000000100000c06 t`datecmp(a=date at 0x00007fff5f400020, b=date at 0x00007fff5f400038) + 22 at t.c:33, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=2, address=0x7fff5f3ffff8)
frame #0: 0x0000000100000c06 t`datecmp(a=date at 0x00007fff5f400020, b=date at 0x00007fff5f400038) + 22 at t.c:33
30 //compare beetween two date
31 int datecmp(date a, date b)
32 {
-> 33 if (a.yyyy<b.yyyy||(a.yyyy==b.yyyy&&a.mm<b.mm)||(a.yyyy==b.yyyy&&a.mm==b.mm&&a.dd<b.dd)) return -1;
34 else if (a.yyyy==b.yyyy&&a.mm==b.mm&&a.dd==b.dd) return 0;
35 return 1;
36 }
您有一个stackoverflow,因为您在行datecal
和dotw
中递归调用97
和65
。问题是:
dotw (line 65) -> datecal (line 97) -> dotw (line 65) -> datecal (line 97) -> ....