C語言的strcpy()和strncpy()函數
C語言7.37K
對於C語言來説,什麼是strcpy()和strncpy()函數呢?這對於想要學習C語言的小夥伴來説,是必須要搞懂的事情,下面是小編為大家蒐集整理出來的有關於C語言的strcpy()和strncpy()函數,一起看看吧!
strcpy()函數
strcpy() 函數用來複制字符串,其原型為:
char *strcpy(char *dest, const char *src);
【參數】dest 為目標字符串指針,src 為源字符串指針。
注意:src 和 dest 所指的內存區域不能重疊,且 dest 必須有足夠的空間放置 src 所包含的字符串(包含結束符NULL)。
【返回值】成功執行後返回目標數組指針 dest。
strcpy() 把src所指的由NULL結束的字符串複製到dest 所指的數組中,返回指向 dest 字符串的起始地址。
注意:如果參數 dest 所指的內存空間不夠大,可能會造成緩衝溢出(buffer Overflow)的錯誤情況,在編寫程序時請特別留意,或者用strncpy()來取代。
示例:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 | /* copy1.c -- strcpy() demo */ #include #include // declares strcpy() #define SIZE 40 #define LIM 5 char * s_gets( char * st, int n); int main( void ) { char qwords[LIM][SIZE]; char temp[SIZE]; int i = 0 ; printf( "Enter %d words beginning with q:" , LIM); while (i < LIM && s_gets(temp, SIZE)) { if (temp[ 0 ] != 'q' ) printf( "%s doesn't begin with q!" , temp); else { strcpy(qwords[i], temp); i++; } } puts( "Here are the words accepted:" ); for (i = 0 ; i < LIM; i++) puts(qwords[i]); return 0 ; } char * s_gets( char * st, int n) { char * ret_val; int i = 0 ; ret_val = fgets(st, n, stdin); if (ret_val) { while (st[i] != '' && st[i] != ' |