C语言字符串连接strcat、strncat用法说明和注意事项

来源:互联网 发布:凌波微步 软件开发 编辑:程序博客网 时间:2024/05/22 09:46
1.strcat1).原型: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);

                                             
0 0
原创粉丝点击