如果问题太混乱,请原谅我!
我有以下结构:
struct msg {
char data[20];
}
struct pkt {
int seqnum;
int acknum;
int checksum;
char payload[20];
};
我有以下结构数组:
struct msg buffer[1000];
现在,我正在做以下事情:
void A_output(struct msg message)
{
//printf("Message in A: %s\n", message.data);
if(inTransit == 0) {
if(hasBuffer > 0) {
printf("%s\n", "Sending from buffer...");
memset(¤tpkt_A->payload, '\0', 20);
strncpy(currentpkt_A->payload, buffer[buffCount].data, 20);
currentpkt_A->seqnum = seq_A;
setChecksum(currentpkt_A);
printf("Checksum from A: %d\n", currentpkt_A->checksum);
printf("Payload from A: %s\n", currentpkt_A->payload);
tolayer3(0, *currentpkt_A);
inTransit = 1;
starttimer(0, increment);
printf("%s\n", "Adding to buffer when sending directly...");
strncpy(buffer[hasBuffer].data, message.data, 20);
hasBuffer++;
buffCount++;
}
else {
printf("Sending directly...\n");
memset(¤tpkt_A->payload, '\0', 20);
strncpy(currentpkt_A->payload, message.data, 20);
currentpkt_A->seqnum = seq_A;
setChecksum(currentpkt_A);
printf("Checksum from A: %d\n", currentpkt_A->checksum);
printf("Payload from A: %s\n", currentpkt_A->payload);
tolayer3(0, *currentpkt_A);
starttimer(0, increment);
inTransit = 1;
}
}
else {
printf("%s\n", "Adding to buffer when in transit...");
strncpy(buffer[hasBuffer].data, message.data, 20);
hasBuffer++;
}
printf("Buffer now has: \n");
for(int i = 0; i<hasBuffer; i++)
printf("%s\n", buffer[i].data);
}
问题是,当我添加到缓冲区并将其打印出来时,我可以看到以下内容:
在第一个添加缓冲区是:
aaaaaaaaaaaaaaaaaaaa
在第二个添加缓冲区是:
aaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbb
bbbbbbbbbbbbbbbbbbbb
在第三个添加缓冲区是:
aaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbcccccccccccccccccccc
bbbbbbbbbbbbbbbbbbbbcccccccccccccccccccc
cccccccccccccccccccc
也就是说,它被添加到数组的每个单元格的末尾,然后是新单元格。我似乎无法弄清楚为什么会这样。