串口通讯中的字符串连接问题。
引言
调试串口通讯时,碰到了一个问题,就是如何在C语言中实现两个字符串连接。第一反应这,这还不简单,用strcat就行了呀,谁知随着深入研究,发现了一些自己平时没有注意到的问题。
正文
需求:
希望实现向串口中发送0x01 0x11 0x10 0x13 0x01 0x12的指令,但是该指令是由0x01 0x11 0x10 0x13 和 0x01 0x12两条指令组合而成。
方案一:
使用strcat实现:
函数原型:extern char *strcat(char *dest, const char *src);
实现代码如下:
1 #include <ansi_c.h> 2 #include <stdio.h> 3 #include <string.h> 4 5 main() 6 { 7 //the first command 8 unsigned char cCommandFirst[6] = "\x01\x11\x10\13"; 9 10 //the second command 11 const unsigned char cCommandSecond[2] = "\x01\0x12"; 12 13 //connect two strings 14 strcat(cCommandFirst,cCommandSecond); 15 16 //show string 17 for(int i = 0; i < 6; i ++) 18 { 19 printf("%X\t",cCommandFirst); 20 } 21 22 getchar(); 23 }
输出结果:1 11 10 13 1 12
原本以为到此就结束了,但是由于在使用的过程中,第二个指令会出现0x00的情况,所以就出现了下面这一幕:
1 #include <ansi_c.h> 2 #include <stdio.h> 3 #include <string.h> 4 5 main() 6 { 7 //the first command 8 unsigned char cCommandFirst[6] = "\x01\x11\x10\13"; 9 10 //the second command 11 const unsigned char cCommandSecond[2] = "\x00\0x12"; 12 13 //connect two strings 14 strcat(cCommandFirst,cCommandSecond); 15 16 //show string 17 for(int i = 0; i < 6; i ++) 18 { 19 printf("%X\t",cCommandFirst); 20 } 21 22 getchar(); 23 }
输出结果:1 11 10 13 0 0
为什么会出现最后添加的第二条指令全部变成了0了呢?
分析strcat函数原型:
1 char *strcat(char *dest, const char *src) 2 { 3 assert(src && dest); 4 char *tmp = dest; 5 while (*dest) 6 dest++; 7 while ((*dest++ = *src++) != '\0'); 8 return tmp; 9 }
通过分析可以发现,在第二个while循环时,它的判断调试是第二条指令是否出现\0,而恰巧在发送第二条指令时,出现了\0,从而出现上述现象。
方案二:
为了上述问题,我们尝试使用memcpy函数:
函数原型:void *memcpy(void *dest, const void *src, size_t n);
首先还是看看函数的实现:
1 void* memcpy(void* dest, const void* src, size_t count) 2 { 3 assert(src && dest); 4 5 char* tmp_dest = (char*)dest; 6 7 const char* tmp_src = (const char*)src; 8 9 10 while (count--) 11 *tmp_dest++ = *tmp_src++; 12 13 return dest; 14 }
从实现可以发现,在连接两个字符串时的判断调试是根据要求的截取第二条指令的长度。
下面使用memcpy实现两个字符串连接:
1 #include <ansi_c.h> 2 #include <stdio.h> 3 #include <string.h> 4 5 main() 6 { 7 //the first command 8 unsigned char cCommandFirst[6] = "\x01\x11\x10\13"; 9 10 //the second command 11 const unsigned char cCommandSecond[2] = "\x00\0x12"; 12 13 //connect two strings 14 //strcat(cCommandFirst,cCommandSecond); 15 memcpy(cPosition + 4,cdata,2);//because the first commands have four items. so we connect the second one from +4 address. 16 17 //show string 18 for(int i = 0; i < 6; i ++) 19 { 20 printf("%X\t",cCommandFirst); 21 } 22 23 getchar(); 24 }
输出结果:1 11 10 13 0 12
完美解决!!
总结:
在使用strcat连接两个字符串时,如果第二个字符中出现'\0'的内容时,这是strcat功能失效。需要使用memcpy函数实现连接两个字符串。

浙公网安备 33010602011771号