C 一个来自结构 tm 的变量消失了



我正在编写一个程序,在其中获取当前周数和当前年数,并在以后的其他函数中使用它们。我注意到在某个时候,我在struct WYDay date_retrieval()函数中保存在Day.weekNumb中的当前周数不再显示并且无法使用它,但我能够找到它消失在哪一行。在数据消失的行中,我试图在字符串的末尾放置一个 NULL 终止符,以便以后可以毫无问题地使用它。我在行前后放置了 2 个printf(),以查看变量在行执行后不显示任何内容。

我知道我的代码现在很混乱,但我正在努力让它暂时工作。我已经输入了我认为我可能搞砸了某些东西的所有功能。感谢帮助和理解问题。

struct WYDay
{
char yearNumb[4];
char weekNumb;
};

int main ()
{
char usrOption;
int fileExists = 0;
int *randValues = NULL;
struct WYDay Days;
puts("This is the math and programming schedule check!n"
"Would you like to see what you've done this week or add something? 
nn"
"1.See your progress!n2.Check what you've done!nnn");
usrOption = user_input();
Days = date_retrieval();
fileExists = first_time_date_check(Days);
if(Days.weekNumb == '1' || fileExists == 0)
{
randValues = schedule_rand();
date_save(Days);
}
file_manip(Days, fileExists, randValues, usrOption);
if(randValues != NULL)
{
free(randValues);
}
printf("n{%c}n", Days.weekNumb);
return 0;
}

struct WYDay date_retrieval()
{
char *yearNumbP;
int iterat = 0;
time_t currentDate;
struct WYDay Day;
struct tm *Date;
time(&currentDate);
Date = localtime(&currentDate);
Day.weekNumb = week_day(Date);
yearNumbP = year_day(Date);
for(iterat = 0; iterat < 4; iterat++)
{
Day.yearNumb[iterat] = yearNumbP[iterat];
}
printf("n{%c}n", Day.weekNumb);
Day.yearNumb[4] = '';       /*This line does something to the week number*/
printf("n{%c}n", Day.weekNumb);
free(yearNumbP);
return Day;
}

char week_day(struct tm *Date)
{
char numbOfWeekDay[2];
char weekDay;
strftime(numbOfWeekDay, 2, "%w", Date);
weekDay = numbOfWeekDay[0];
if(weekDay == '0')
{
weekDay = '7';
}
return weekDay;
}

char *year_day(struct tm *Date)
{
char *numbOfYearDay = calloc(4, sizeof(char));
strftime(numbOfYearDay, 4, "%j", Date);
return numbOfYearDay;
}

代码将Day.yearNumb数组声明为包含四个元素的数组:

char yearNumb[4];

但是,它正在设置 4 元素数组的第 5 个元素:

Day.yearNumb[4] = '';

(请记住,元素从 0 开始编号!因此,此代码表现出未定义的行为。实际发生的很可能是下一个结构成员设置为 0。

你需要在 yearNumb 中增加一个元素,这样它就可以容纳 5 个字符 - 年份的四个字符,加上 nul 终止符。

这是定义一个包含 4 个元素的数组。

char yearNumb[4];

这是访问该数组中的第 5 个元素。

Day.yearNumb[4] = '';

因此,自然地,通过将值放在数组末尾之外的位置,您将影响结构中它之后的任何内容。

我认为您应该为终止''留下内存。否则,它将在内存中的下一个元素上溢出。

struct WYDay
{
char yearNumb[5];
char weekNumb[2];
};

现在yearNumb[4] = ''工作了。你也可以做weekNumb[1] = ''

最新更新