Loading

【转】在使用strncpy, snprintf, strncat时,到底size要定义多大呢?

关于strncpy()、strncat()中的参数n的问题?

  • char * strncpy ( char * destination, const char * source, size_t num )

功能:从source中复制num个字符到destination中。

1、若strlen(source) < num,则复制strlen(source)个字符和num-strlen(source)个'\0'到destination中。

2、若strlen(source) > num,则复制num个字符到destination中。注意:如果source前num个字符都没有'\0',那么复制过去num个字符是没有'\0'的。

  • char * strncat ( char * destination, const char * source, size_t num );

功能:从source中复制num个字符拼接到destination末尾。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void)
{
    char str[6] = {0};

    /* strncat()。始终计算str的剩余长度,并告知strncat()函数,防止数组越界 */
    strncat(str, "hello", sizeof(str) - strlen(str) - 1);
    printf("str:%s, len:%d\n", str, (int)strlen(str));

    /* 由于sizeof(str) - strlen(str) - 1计算结果为0,故不允许字符串拼接 */
    strncat(str, "world", sizeof(str) - strlen(str) - 1);
    printf("str:%s, len:%d\n", str, (int)strlen(str));

    /* strncpy() 。始终计算str的剩余长度,并告知strncpy()函数,防止数组越界*/
    memset(str, 0, sizeof(str));
    strncpy(str, "hello", sizeof(str) - 1);
    printf("str:%s, len:%d\n", str, (int)strlen(str));

    /* sizeof(str) - 1计算结果为5,尽管待拷贝的字符串长度是11,也只能拷贝5个字符  */
    memset(str, 0, sizeof(str));
    strncpy(str, "hello world", sizeof(str) - 1);
    printf("str:%s, len:%d\n", str, (int)strlen(str));
    
    return 0;
}

参考

在使用strncpy, snprintf, strncat时,到底size要定义多大呢?

posted @ 2024-04-16 17:04  eiSouthBoy  阅读(86)  评论(0)    收藏  举报