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

Pet*_*nes 2 c string malloc strncpy

我想知道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)

Jer*_*fin 6

我根本不会用strncpy它.至少如果我理解你要做什么,我可能会做这样的事情:

char *duplicate(char *input, size_t max_len) {
    // compute the size of the result -- the lesser of the specified maximum
    // and the length of the input string. 
    size_t len = min(max_len, strlen(input));

    // allocate space for the result (including NUL terminator).
    char *buffer = malloc(len+1);

    if (buffer) {
        // if the allocation succeeded, copy the specified number of 
        // characters to the destination.
        memcpy(buffer, input, len);
        // and NUL terminate the result.
        buffer[len] = '\0';
    }
    // if we copied the string, return it; otherwise, return the null pointer 
    // to indicate failure.
    return buffer;
}
Run Code Online (Sandbox Code Playgroud)