snprintf vs. strcpy (etc.) in C

后端 未结 7 1814
长发绾君心
长发绾君心 2021-01-02 07:35

For doing string concatenation, I\'ve been doing basic strcpy, strncpy of char* buffers. Then I learned about the snprintf and friends

7条回答
  •  太阳男子
    2021-01-02 08:32

    All *printf functions check formatting and expand its corresponding argument, thus it is slower than a simple strcpy/strncpy, which only copy a given number of bytes from linear memory.

    My rule of thumb is:

    • Use snprintf whenever formatting is needed.
    • Stick to strncpy/memcpy when only need to copy a block of linear memory.
    • You can use strcpy whenever you know exatcly the size of buffers you're copying. Don't use that if you don't have full control over the buffers size.

提交回复
热议问题