c语言中strncp函数,函数原型、头文件
1、函数原型
#include <stdio.h> char *strncpy(char *s1, const char *s2, size_t n) { char *tmp = s1; while(n) { if(!(*s1++ = *s2++)) //此处是if语句,不能用while、for等,此句要和n--;同步执行 break; n--; } // 当字符串str2大于n时,s1指针最后指向的并不是null, 况且当 str2小于n时,指针最后已经指向了null, 为什么还要 执行*s1++ = '\0'呢? 程序是否有问题??? while(n--) *s1++ = '\0'; return tmp; } int main(void) { char str1[128] = "abcdefghij"; char str2[128]; printf("str2: "); scanf("%s", str2); unsigned n; printf("n = "); scanf("%u", &n); strncpy(str1, str2, n); printf("str1: %s\n", str1); return 0; }
2、改进
#include <stdio.h> char *strncpy(char *s1, const char *s2, size_t n) { char *tmp = s1; while(n) { if(!(*s1++ = *s2++)) break; n--; } *s1 = '\0'; return tmp; } int main(void) { char str1[128] = "abcdefghij"; char str2[128]; printf("str2: "); scanf("%s", str2); unsigned n; printf("n = "); scanf("%u", &n); strncpy(str1, str2, n); printf("str1: %s\n", str1); return 0; }
3、头文件
#include <stdio.h> #include <string.h> int main(void) { char str1[128] = "abcdefghijk"; char str2[128]; printf("str2: "); scanf("%s", str2); unsigned n; printf("n = "); scanf("%u", &n); strncpy(str1, str2, n); printf("str1: %s\n", str1); return 0; } //看来程序没有问题,原始程序就是这种设计,复制的字符串数目少于字符串长度时,接收字母串末尾不用处理。如下图:(改进2可以实现仅保留复制的部分,使其成为字符串)