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