c函数调用堆栈问题

bisal(Chen Liu)
博客专家认证
2009-11-18 09:01:54
请问下面code:
char *get_millitm()
{
struct timeval tms;
char tstr[100];
char *time;
timerclear(&tms);
gettimeofday(&tms, NULL);
strftime(tstr, 100, "%X", localtime(&tms.tv_sec));
/* tv_usec是微秒,除以1000转换为毫秒 */
sprintf(time, "%s.%d", tstr, tms.tv_usec/1000);
return time;
}
如果在另一个函数中调用它,例如:
void method(){
printf("%s\n", get_millitm());
}
这样是不是再次调用函数,有可能将time覆盖,所以应该使用下面
void get_millitm(char *time)
{
struct timeval tms;
char tstr[100];
timerclear(&tms);
gettimeofday(&tms, NULL);
strftime(tstr, 100, "%X", localtime(&tms.tv_sec));
/* tv_usec是微秒,除以1000转换为毫秒 */
sprintf(time, "%s.%d", tstr, tms.tv_usec/1000);
}
这样在其它函数中使用time变量就不会有两次调用出现问题的情况了。

可以解释下原因么?谢谢!
...全文
138 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
bisal(Chen Liu) 2009-11-20
  • 打赏
  • 举报
回复
我用这个语句打印是:段错误Segmentation Fault(coredump)
void main()
{
char *str;
get_millitm(&str);
printf("str=%s\n", *str);
}
poloyou 2009-11-19
  • 打赏
  • 举报
回复
看了你的帖子没有可看明白你问的意思,
按我的理解:
char *get_millitm()
{
struct timeval tms;
char tstr[100];
char *time;
timerclear(&tms);
gettimeofday(&tms, NULL);
strftime(tstr, 100, "%X", localtime(&tms.tv_sec));
/* tv_usec是微秒,除以1000转换为毫秒 */
sprintf(time, "%s.%d", tstr, tms.tv_usec/1000);
return time;
}




void get_millitm(char *time)
{
struct timeval tms;
char tstr[100];
timerclear(&tms);
gettimeofday(&tms, NULL);
strftime(tstr, 100, "%X", localtime(&tms.tv_sec));
/* tv_usec是微秒,除以1000转换为毫秒 */
sprintf(time, "%s.%d", tstr, tms.tv_usec/1000);
}

这个函数如果你要得到函数里面time的值的话就会有问题,按我的理解应该这样来做,但不知道对不对:


sprintf(time, "%s.%d", tstr, tms.tv_usec/1000);
是往字符串time中打印,相当于time = "你要打印的字符串";这个要打印的字符串是常量,分配的是静态地址空间,你这样在函数中返回其地址是完全可以获得你要的字符串;

void get_millitm(char **time)
{
struct timeval tms;
char tstr[100];
timerclear(&tms);
gettimeofday(&tms, NULL);
strftime(tstr, 100, "%X", localtime(&tms.tv_sec));
/* tv_usec是微秒,除以1000转换为毫秒 */
sprintf(*time, "%s.%d", tstr, tms.tv_usec/1000);
}

main()
{
char *str;
get_millitm(&str);
return;

}

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧