小编Pet*_*nes的帖子

在C中更有效地使用strncpy复制n个字符

我想知道strncpy考虑到max一些字符,是否有一种更干净,更有效的方法来做以下事情.我觉得自己过度了.

int main(void)
{

        char *string = "hello world foo!";
        int max = 5;

        char *str = malloc (max + 1);
        if (str == NULL)
                return 1;
        if (string) {
                int len = strlen (string);
                if (len > max) {
                        strncpy (str, string, max);
                        str[max] = '\0';
                } else {
                        strncpy (str, string, len);
                        str[len] = '\0';
                }
                printf("%s\n", str);
        }
        return 0;
}
Run Code Online (Sandbox Code Playgroud)

c string malloc strncpy

2
推荐指数
1
解决办法
8667
查看次数

标签 统计

c ×1

malloc ×1

string ×1

strncpy ×1