1、函數原型
#includechar *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、改進
#includechar *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;
}
#include#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可以實作僅保留複制的部分,使其成為字元串)