C語言字符串連接strcat、strncat用法說明和注意事項

1.strcat
1).原型:char * strcat ( char * destination, const char * source );
2).作用:在destination的後面連接source字符串,destination的'\0'會被source的第一個字符替換,並且在新字符串的結尾會加上'\0'。
3).參數:
	(1).destination,指向目標字符串,足夠的大,能夠容納連接成的字符串。
	(2).source,要連接的字符串,且不能與destination有內存重疊。
4).返回值: destination

正確示例:
  (1).
  
  char str[50] = "What \0";
  strcat (str,"is your name?");
  puts (str);

(2).
  char *str = (char *)malloc(50);
  strcpy(str,"What ");
  strcat (str,"is your name?");
  puts (str);
  free(str);
典型錯誤:
  (1).

  char str[] = "What ";
  strcat (str,"is your name?");//會發生運行時錯誤,因爲str的size是6,現在又在後面連接了一個字符串,從而產生錯誤
  puts (str);

  (2).
  
  char *str = (char *)malloc(50);
  strcpy(str,"What is yourname?");
  strcat(str,str+5);//這個地方有內存重疊,會發生運行時錯誤
  puts (str);
  free(str);


2.
1).原型:char * strncat ( char * destination, const char * source, size_t num );
2).作用:在destination的後面連接source字符串的前num個字符,destination的'\0'會被source的第一個字符替換,並且在新字符串的結尾會加上'\0'。如果source字符串的大小小於num,那麼僅會拷貝source裏面的全部東西。
3).參數:
	(1).destination,指向目標字符串,足夠的大,能夠容納連接成的字符串。
	(2).source,要連接的字符串。
	(3).num,最大連接的字符數,無符號整數。
4).返回值: destination

正確示例:
  (1).
  
  char str[50] = "What \0";
  strncat (str,"is your name?",strlen(“is your name?”));
  puts (str);
(2).
  char *str = (char *)malloc(50);
  strcpy(str,"What ");
  strncat (str,"is your name?",strlen(“is your name?”));
  puts (str);
  free(str);

典型錯誤:
  (1).

  char str[] = "What ";
  strncat (str,"is your name?",strlen(“is your name?”));//會發生運行時錯誤,因爲str的size是6,現在又在後面連接了一個字符串,從而產生錯誤
  puts (str);

  (2).

  char *str = (char *)malloc(50);
  strcpy(str,"What is yourname?");
  strncat(str,str+5,-1);這地方傳入的是個負數,實際程序想要接收的是正數,就會強制把負數轉化爲正數,
也就是個非常大的正數,已經超過了str的size,所以也會產生運行時錯誤。
  puts (str);
  free(str);


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章