C struct tm 中的变量消失

标签 c date

我正在编写一个程序,在其中获取当前周数和当前年份数,并稍后在其他函数中使用它们。我注意到在某个时候,我保存在 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? 
\n\n"
       "1.See your progress!\n2.Check what you've done!\n\n\n");

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] = '\0';       /*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 开始编号!)因此,此代码表现出未定义的行为。实际发生的情况很可能是下一个结构成员被设置为 0。

您需要在yearNumb中添加一个额外的元素,以便它可以容纳5个字符 - 年份的四个字符,加上nul终止符。

关于C struct tm 中的变量消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51364188/

相关文章:

c - 在C中读取包含十六进制值的char数组

c - 将字符回显到C中的串行端口

c - 长整数计算错误

javascript - JMeter BSF 断言 - 比较日期变量

date - 如何在 Hadoop Hive 中给定时间戳获取一周第一天的日期?

c# - 确定日期是否为 "work day off"

c - 不使用互斥锁保护双变量

c - 使不按预期工作

java - 在java中将日期格式从一种更改为另一种

ruby - 将字符串日期格式从 "17-Nov-2011"转换为 "11/17/11"