在strcpy之后具有重复值的char []
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在strcpy之后具有重复值的char []相关的知识,希望对你有一定的参考价值。
我有一个带有两个char数组变量(id和id_partner_expected)的结构,当我在第二个数组上使用strcpy时,第一个数组也会被更改。我尝试了所有我知道的,但没有预期的结果:(
#define SIZE_CLIENT_ID 15
struct client_infos {
char addr[INET_ADDRSTRLEN];
int socket;
char id[SIZE_CLIENT_ID];
char id_partner_expected[SIZE_CLIENT_ID];
struct client_infos* partner;
};
char buffer_received[MAX_CLIENT_IO];
while ((len_received = recv(c->socket, buffer_received, MAX_CLIENT_IO, 0)) > 0) {
if (strlen(c->id) == 0) {
//First step: Identify the client
strcpy(c->id, buffer_received); // FIRST LOOP
} else if (strlen(c->id_partner_expected) == 0) {
//Second step: Identify/Connect the partner
strcpy(c->id_partner_expected, buffer_received); // SECOND LOOP
}
printf("Received %d bytes from client %s, with id %s", len_received, c->addr, c->id);
printf("%d
", strlen(c->id));//STRCPY DUPLICATING CONTENT OF C->ID ???!!!
}
结果:
1º循环:
从客户端0.0.0.0收到15个字节,ID为0000654987321 15
2º循环:
从客户端0.0.0.0收到15个字节,ID为0000654987321 6544sssss5555 30
但预期的结果是:
2º循环:
从客户端0.0.0.0收到15个字节,ID为0000654987321 15
原始来源:https://github.com/fernandobatels/blitz-p2p-bridge/blob/master/src/api.h https://github.com/fernandobatels/blitz-p2p-bridge/blob/master/src/api.c
谢谢你的帮助:)
答案
C字符串零终止。从网络收到的字符串显然不是。接收数据后,您需要对字符串进行零终止:
...
while ((len_received = recv(c->socket, buffer_received, MAX_CLIENT_IO, 0)) > 0) {
buffer_received[len_received] = 0; // add this line
if (strlen(c->id) == 0) {
...
另请注意,由于您的最大ID长度(以及从网络接收的最大数据量)为15,您需要将数组扩展一个字符,以便为终止零点腾出空间:
struct client_infos {
char addr[INET_ADDRSTRLEN];
int socket;
char id[SIZE_CLIENT_ID + 1];
char id_partner_expected[SIZE_CLIENT_ID + 1];
struct client_infos* partner;
}
char buffer_received[MAX_CLIENT_ID + 1];
以上是关于在strcpy之后具有重复值的char []的主要内容,如果未能解决你的问题,请参考以下文章