自定义函数获取buf时snprintf中sizeof(buf)出现问题导致赋值不全

警告可能出现的问题:
directive output truncated writing 16 bytes into a region of size 4 [-Wformat-truncation=]

warning: argument to ‘sizeof’ in ‘snprintf’ call is the same expression as the destination; did you mean to provide an explicit length? [-Wsizeof-pointer-memaccess]

note: assuming directive output of 4 bytes


出现了问题记录一下,防止脑子不好忘记了。
直接上代码看情况:
在main函数中调用了report_tempRH_json,传入buf,获取数据。但是获取的数据是不全的。

#include <stdio.h>

void report_tempRH_json(char *buf);

int main(int argc, char *argv[])
{
    char temp_hum_buf[256];
    
    report_tempRH_json(temp_hum_buf);
    printf("temp_hum_buf:%s\n", temp_hum_buf);

    return 0;

}

void report_tempRH_json(char *buf)
{
    float temperature = 66.6666;
    float humidity = 55.5555;
    snprintf(buf, sizeof(buf), "{\"Temperature\":\"%.2f\", \"Humidity\":\"%.2f\"}", temperature, humidity);

    printf("buf:%s\n", buf);
}

在这里插入图片描述


找了一圈没找到答案,最后发现,sizeof(buf)这儿出现了问题:
在main主函数中sizeof(buf)=256
在自定义函数中sizeof(buf)=8
所以字节在自定义函数中将sizeof(buf)改成256就可,或者宏定义大小,比较方便。

#include <stdio.h>

void report_tempRH_json(char *buf);

int main(int argc, char *argv[])
{
    char temp_hum_buf[256];

    report_tempRH_json(temp_hum_buf);
    printf("Main function sizeof(temp_hum_buf): %d\n", sizeof(temp_hum_buf));
    
    printf("temp_hum_buf:%s\n", temp_hum_buf);

    return 0;

}

void report_tempRH_json(char *buf)
{
    float temperature = 66.6666;
    float humidity = 55.5555;
    snprintf(buf, 256, "{\"Temperature\":\"%.2f\", \"Humidity\":\"%.2f\"}", temperature, humidity);

    printf("Custom function sizeof(buf): %s\n", buf);
    printf("sizeof(buf): %d\n", sizeof(buf));
}

在这里插入图片描述


但是在实际情况下我们不会传buf的,一般是一个函数就实现一个功能,我们的目的是在buf中放数据,那就直接在自定义函数中进行就可以了呗。并且buf用完之后出了自定义函数之后就释放了,方便。

#include <stdio.h>

void report_tempRH_json();

int main(int argc, char *argv[])
{
    report_tempRH_json();

    return 0;

}

void report_tempRH_json()
{
    char  buf[256];
    float temperature = 66.6666;
    float humidity = 55.5555;

    snprintf(buf, sizeof(buf), "{\"Temperature\":\"%.2f\", \"Humidity\":\"%.2f\"}", temperature, humidity);

    printf("sizeof(buf): %s\n", buf);
    printf("sizeof(buf): %d\n", sizeof(buf));
}

在这里插入图片描述


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值