[C指针]指针与字符串:snprintf() 用函数初始化字符串,再返回

学习笔记

《深入理解C指针》
http://www.ituring.com.cn/book/1147
第5章 指针与字符串

用函数初始化字符串,再返回

1、给函数传递一个空缓冲区让它填充并返回

  • 必须传递缓冲区的地址和长度;
  • 调用者负责释放缓冲区;
  • 函数通常返回缓冲区的指针。
Item: Axle Quantity: 25 Weight: 45
  • Item: Axle Quantity: 25 Weight: 45 被填到了buffer数组里面;
  • 函数返回的就是传入的buffer数组的地址;

完整源码

#include 
#include 
#include 

char* format(char *buffer, size_t size,
        const char* name, size_t quantity, size_t weight) 
{
    snprintf(buffer, size, "Item: %s Quantity: %u Weight: %u",
            name, quantity, weight);
    
    return buffer;
}

int main()
{   
    char buffer[100];
    printf("%s\n",format(buffer,sizeof(buffer),"Axle",25,45));
    printf("%s\n", buffer);

    return 0;
}

参考资料

  • [Linux C 字符串函数 sprintf()、snprintf() 详解]
    https://www.cnblogs.com/52php/p/5724390.html

你可能感兴趣的:([C指针]指针与字符串:snprintf() 用函数初始化字符串,再返回)