为什么当调用另一个函数时,这个字符数组的值会发生变化
Why is this array of chars changing value when another function is called?
为什么我的comportstr在这段代码中被更改为垃圾值?我不明白如果我的char数组没有任何改变,它怎么会改变值。这两份打印报表之间没有其他内容。
int main(int argc, char* argv[])
{
char comportstr[10];
sprintf(comportstr,"COM%d",COMPORT_NUM);
if(DEBUGGING) fprintf(stderr,"str is: %sn", comportstr); //prints str is: COM3
sprintf(curtime , "%s" , currentDateTime());
if(DEBUGGING) fprintf(stderr,"str is: %sn", comportstr); //prints str is: ;32
}
以下是currentDateTime的作用。它根本不会修改comportstr。
// Gets current date/time, format is YYYY-MM-DD.HH;mm;ss
const std::string currentDateTime()
{
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
// Visit http://www.cplusplus.com/reference/clibrary/ctime/strftime/
// for more information about date/time format
strftime(buf, sizeof(buf), "%Y-%m-%d.%H;%M;%S", &tstruct);
return buf;
}
在currentDateTime()
函数中,您将返回一个传递给sprintf()
的vararg接口的std::string
。这不起作用,因为您无法将标准布局类型传递给vararg接口。也就是说,对sprintf()
的第二次调用会导致未定义的行为。
你可以通过使用来避免这个问题
sprintf(curtime , "%s" , currentDateTime().c_str());
或者,实际上,
strcpy(curtime, currentDateTime().c_str());
sprintf(curtime , "%s" , currentDateTime());
currentDateTime
函数返回一个std::string
,但%s
仅用于C样式字符串。您需要currentDateTime().c_str()
。你的编译器应该给你一个警告。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 在C 中创建一个不可变化的2D数组
- C++:数组的大小在传递给函数后发生变化
- c ++,数组的值在某处意外变化,你能帮我找出在哪里吗?
- 用于处理索引不断变化的数组的数据结构
- (C++)函数完成后,堆栈上分配的数组发生了什么变化
- C++-类成员函数中的数组值自发变化
- 为什么当调用另一个函数时,这个字符数组的值会发生变化
- 计算变化数组中预期的反演次数
- 数组的值是随机变化的
- 动态二维数组,列大小变化,不知道提前
- STL push_back:在推送动态变化的数组时修改以前的值
- 查找数组中数字符号的变化量