對於C語言來說,什麼是strcpy()和strncpy()函式呢?這對於想要學習C語言的小夥伴來說,是必須要搞懂的事情,下面是小編為大家蒐集整理出來的有關於C語言的strcpy()和strncpy()函式,一起看看吧!
strcpy()函式
strcpy() 函式用來複制字串,其原型為:
char *strcpy(char *dest, const char *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] != ' |