c语言中的字符串拼接

在看内核源码时,看到这样一段代码:

int __init ip_vs_protocol_init(void)
{
	char protocols[64];
#define REGISTER_PROTOCOL(p)			\
	do {					\
		register_ip_vs_protocol(p);	\
		strcat(protocols, ", ");	\
		strcat(protocols, (p)->name);	\
	} while (0)

	protocols[0] = '\0';
	protocols[2] = '\0';
#ifdef CONFIG_IP_VS_PROTO_TCP
	REGISTER_PROTOCOL(&ip_vs_protocol_tcp);
#endif
#ifdef CONFIG_IP_VS_PROTO_UDP
	REGISTER_PROTOCOL(&ip_vs_protocol_udp);
#endif
#ifdef CONFIG_IP_VS_PROTO_SCTP
	REGISTER_PROTOCOL(&ip_vs_protocol_sctp);
#endif
#ifdef CONFIG_IP_VS_PROTO_AH
	REGISTER_PROTOCOL(&ip_vs_protocol_ah);
#endif
#ifdef CONFIG_IP_VS_PROTO_ESP
	REGISTER_PROTOCOL(&ip_vs_protocol_esp);
#endif
	pr_info("Registered protocols (%s)\n", &protocols[2]);

	return 0;
}

不太理解,研究了一番,记录一下自己的理解。
1 怎么判断字符串的结尾?
每个字节都是8位的2进制,如果每一位都为0,则表示字符串的末尾。申请的数组,每个字节的值是不确定的,除非手动清零,否则不一定为0.
2 字符串怎么拼接的?
先判断两个字符串的末尾,然后将两个字符串拼接到一起,并将字符串最末尾设置为0。
3 为什么要将位置0和位置2都置为0?
protocols[0] = ‘\0’;
protocols[2] = ‘\0’;
将位置0置为0表示这是一个空字符串。
拼接的时候,前面默认带了", "这两个符号。所以从位置2开始输出,可以过滤掉前面多余的“, ”,那么为什么需要将位置2也置为0呢?这是因为如果没有发生拼接的情况下,需要保证输出为空。

附测试代码:

/*strcatTest.c*/
#include <stdio.h>
#include <string.h>

int main ()
{
	char protocols[51];
  
  protocols[0] = '\0';
	protocols[2] = '\0';

  printf("postition 0:%d\n", (int) protocols[0]);
  printf("postition 0:%d\n", (int) protocols[2]);
  printf("postition 3:%d\n", (int) protocols[3]);
  printf("postition 4:%d\n", (int) protocols[4]);
  printf("postition 49:%d\n", (int) protocols[49]);
   printf("Registered protocols 2 (%s)\n", &protocols[2]);
  
  printf("Registered protocols  3(%s)\n", &protocols[3]);
  
  printf("Registered protocols  4(%s)\n", &protocols[4]);
  
  printf("Registered protocols  49(%s)\n", &protocols[49]);
 /* 
  strcat(protocols, ", ");
  
  printf("Registered protocols (%s)\n", protocols);
  printf("Registered protocols (%s)\n\n", &protocols[2]);
  
  strcat(protocols, "tcp");	

  printf("Registered protocols (%s)\n", protocols);
  printf("Registered protocols (%s)\n\n", &protocols[2]);
  
  strcat(protocols, ", ");
  strcat(protocols, "udp");	*/
 
	return(0);
}

测试结果:

root@debian2:~/test# gcc strcatTest.c -o strcatTest;./strcatTest
postition 0:0
postition 0:0
postition 3:0
postition 4:-32
postition 49:65
Registered protocols 2 ()
Registered protocols  3()
Registered protocols  4(▒n▒▒▒▒)
Registered protocols  49(A)
root@debian2:~/test#

猜你喜欢

转载自blog.csdn.net/qq_31567335/article/details/89609948