Home > Common Problem > body text

How to use strncpy

小老鼠
Release: 2023-11-28 11:13:34
Original
1777 people have browsed it

strncpy是C语言中的一个函数,用于将一个字符串复制到另一个字符串中,且可以指定复制的字符数。其函数原型如下:

char *strncpy(char *dest, const char *src, size_t n);
Copy after login

这个函数的参数解释如下:

  • dest:目标字符串,即要复制到的位置。
  • src:源字符串,即要从中复制的字符串。
  • n:要复制的最大字符数(包括空字符 '\0')。

strncpy 函数将 src 字符串的前 n 个字符复制到 dest 字符串中。如果 src 的长度小于 n,那么在 dest 字符串的剩余部分会填充 '\0'。否则,dest 将不会以 '\0' 结尾。

下面是一个简单的例子:

#include <stdio.h>  
#include <string.h>  
  
int main() {  
    char dest[20];  
    const char *src = "Hello, World!";  
    strncpy(dest, src, 5);  
    dest[5] = '\0'; // 确保 dest 以 '\0' 结尾  
    printf("%s\n", dest); // 输出 "Hello"  
    return 0;  
}
Copy after login

在这个例子中,我们使用 strncpy 将 src 字符串的前5个字符复制到 dest 字符串。由于我们确保了 dest[5] 是 '\0',所以打印 dest 时只输出到第一个 '\0'。这样,输出的字符串就是 "Hello"。

The above is the detailed content of How to use strncpy. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!