C 如何从函数中获取字符串并将其赋值?
我有一个函数C 如何从函数中获取字符串并将其赋值?,c,C,我有一个函数print\u date\u time,我想将日期作为字符串返回。然后我想将该时间分配给一个新变量,并在main中打印它。之后,我想在另一个函数中使用它 #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <windows.h> #include <time.h> #include <assert.h> static char*
print\u date\u time
,我想将日期作为字符串返回。然后我想将该时间分配给一个新变量,并在main
中打印它。之后,我想在另一个函数中使用它
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <windows.h>
#include <time.h>
#include <assert.h>
static char* print_date_time()
{
time_t t = time(NULL);
struct tm* tm = localtime(&t);
char s[64];
assert(strftime(s, sizeof(s), "%c", tm));
//printf("TIME TIME: %s\n", s);
return s;
}
/****************************************
*
* MAIN FUNCTION
*
****************************************/
int main(int argc, char** argv)
{
char *date;
date = print_date_time();
printf("time is: %s\n",date);
//assert(strftime(tab, sizeof(tab), "%c", print_date_time()));
//print_date_time();
return 0;
}
#包括
#包括
#包括
#包括
#包括
#包括
静态字符*打印日期时间()
{
时间t=时间(空);
struct tm*tm=本地时间(&t);
chars[64];
断言(strftime,sizeof,“%c”,tm));
//printf(“时间:%s\n”,s);
返回s;
}
/****************************************
*
*主要功能
*
****************************************/
int main(int argc,字符**argv)
{
字符*日期;
日期=打印日期时间();
printf(“时间是:%s\n”,日期);
//断言(strftime(tab,sizeof(tab),“%c”,print\u date\u time());
//打印日期和时间();
返回0;
}
我估计是现在
如何从函数中获取字符串并分配给它?
char s[64]
是堆栈分配的数组,您将返回指向该数组的指针,这是未定义的行为。改为在堆上分配s
intsz=64*sizeof(char);
char*s=malloc(sz);
断言(strftime(s,sz,“%c”,tm));
不要像这样使用assert
;仅适用于没有副作用的表达式。我认为函数声明为static
是有原因的。可能建议使用静态字符[64]代码>?此外,您可能不希望在有副作用的表达式上使用assert
。@JL2210生成函数static
只会限制其对同一编译单元的访问,这与存储类static
有很大不同。而且,assert
是用来显示代码更改的上下文的,它已经存在于OP的代码中了。啊,对了。忘记了静态
如何应用于函数。但是,您可以添加关于断言的注释;此代码不适用于定义的NDEBUG
。请注意sizeof(char)
定义为1,而int
不是适合大小的类型;改用size\t
。