本地时间() - 分割故障 [英] localtime() - segmentation fault

查看:143
本文介绍了本地时间() - 分割故障的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的code返回的工作日从像29-02-2016的日期,但有时它给了我分割在本地时间故障(电话电报公司)。

I have this code that return the week day from a date like "29-02-2016", but sometimes it gives me segmentation fault in localtime(&t).

int obterDiaSemana(char *str) {
 struct tm tm2;
 if(strptime(str, "%d-%m-%Y", &tm2) != NULL) {
  time_t t = mktime(&tm2);
  return localtime(&t)->tm_wday; //Sunday=0, Monday=1, etc.
 }
 return -1;
}

函数接收:

 char userDate[10]="29-02-2016";

我一直在寻找一个解决方案,但不能解决这个问题。

I've been looking for a solution but cant solve this.

先谢谢了。

如果你需要一些额外的信息只是让我知道。

If you need some additional info just let me know.

推荐答案

您没有初始化结构TM TM2 。当它被传递给strptime,只有在格式字符串指定的成员D-%M-%%Y设置其值,其它保持不变,在这种情况下,未初始化的,所以它们的值是不确定的。

You are not initializing struct tm tm2. When it is passed to strptime, only members specified in the format string "%d-%m-%Y" are set with values, others are left unchanged, in this case uninitialized, so their values are indeterminate.

传递一个部分初始化结构 TM2 来mktime()根据会导致不确定的行为。

Passing that partially initialized struct tm2 to mktime() will result in undefined behavior.

您需要用零pferably初始化一些价值观的结构,$ P $。

You will need to initialize the struct with some values, preferably with zeroes.

和阵列userDate是太小,无法包含29-02-2016

And array userDate is too small to contain "29-02-2016".

这篇关于本地时间() - 分割故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆