strncat _emulations_多次调用忽略改变n?

时间:2014-08-08 10:25:50

标签: c++

对于自学,这里有我的2版strncat(一个带指针+偏移表示法和一个数组版本):

// 08_38.cpp                                                                    
#include <iostream>
#include <cstring>

char * strncatPtr(char * a, char * b, size_t n);
char * strncatArr(char * a, char * b, size_t n);

int main (void) {

   char string1[20] = "foobarqwerty";
   char string2[20] = "asd";

   // strncat                                                                   
   std::cout << "-----------------------" << std::endl;
   std::cout << "--------STRNCAT--------" << std::endl;
   std::cout << "-----------------------" << std::endl;
   std::cout << strncat(string2, string1, 6) << std::endl;
   std::cout << strcpy(string2, "asd") << std::endl;

   std::cout << strncatPtr(string2, string1, 4) << std::endl;
   std::cout << strcpy(string2, "asd") << std::endl;

   std::cout << strncatArr(string2, string1, 3) << std::endl;
   std::cout << strcpy(string2, "asd") << std::endl;

   return 0;
}

// ------------------------------------                                         
char * strncatPtr(char * a, char * b, size_t n){
   unsigned int i = 0;
   // go to the end;                                                            
   for(; *(a+i) != '\0'; i++);
   // and start copying                                                         
   for(unsigned int j = 0;
       ((*(a+i+j) = *(b+j)) != '\0') && (j < n-1);
       j++);
   return a;
}

char * strncatArr(char * a, char * b, size_t n){
   unsigned int i = 0;
   // go to the end;                                                            
   for(; a[i] != '\0'; i++);
   // and start copying                                                         
   for(unsigned int j = 0;
       ((a[i+j] = b[j]) != '\0') && (j < n-1);
       j++);
   return a;
}

我不知道为什么当我测试它时,它会为每个函数调用认为size = 6

-----------------------
--------STRNCAT--------
-----------------------
asdfoobar
asd
asdfoobar
asd
asdfoobar
asd

但是如果我单独测试它们,每次评论2个不同的电话,它们都可以正常工作......你能不能开导我?

1 个答案:

答案 0 :(得分:2)

如果复制的字符数少于连接字符串的长度,那么您不会添加空终止符来指示字符串的结尾。