前言
snprintf函数的功能是格式化输出到字符串中,函数原型为:
int snprintf(char *str, size_t size, const char *fomat, ...)
正常来说,只要会用printf函数写输出语句,应该都能会用该函数。但是,稍有不留神,很可能踩到其中的坑。现将前段时间遇到的一个问题进行简单地分析。
问题
以下是抽取出来的问题代码段:
#include <stdio.h>
#include <iostream>
class A
{
public:
int64_t b;
char* pstr;
int a;
};
int main()
{
char source[128] = "hello world";
char tstr[128] = "\0";
A a;
a.a=0x0001;
a.b=0x00030004;
a.pstr = source;
snprintf(tstr, sizeof(tstr), "b=%ld,str=%s,a=%d\n", a.b, a.pstr, a.a);
printf("%s",tstr);
//printf("%s\nsource address:%ld\n",tstr,