arrays - 为什么接收到的元素总是保存在第一位?
问题描述
我有一个程序 server.c,其中有一个打开的套接字。它接收一些字符串代码(例如“AAA”、“BBB”、“CCC”等)。我有一个数组,我在其中保存一次收到的每个不同的代码。例如,如果我获得了 3 次“AAA”,则将其保存在位置 0 中。然后,如果获得“BBB”,则检查数组中是否还没有另一个“BBB”实例,然后将其保存在同一数组中的下一个位置,即 1,依此类推。问题是到达的元素总是并且在任何情况下都保存在位置 0 中,并且没有正确完成比较。我哪里错了?code 是接收到的字符串。 全局变量是:
char *received[100];
size_t array_size = 0;
我的代码是:
int found = 0;
if(array_size == 0){
printf("This is the first message received.\n");
received[array_size] = code;
array_size = array_size+1;
found= 0;
printf("Code added to array. The number of messages is %d. It contains:\n", (int)array_size);
for(int j=0; j<array_size; j++){
printf("Element n. %d -> %s\n", j, received[j]);
}
}
else
{
printf("This is NOT the first message received. Size of array: %d\n", (int)array_size);
for(int j=0; j<array_size; j++){
printf("Compare %s and %s\n", code, received[j]);
if( (strcmp(code,received[j])) == 0){
found= 1;
}
}
if(found== 0){
received[array_size] = code;
array_size = array_size+1;
}
}
输出:
Element n. 0 -> AAA
*******************received****************
This is NOT the first message received. Size of array: 1
Compare AAA and AAA
*******************received****************
This is NOT the first message received. Size of array: 1
Compare BBB and BBB -----> **Here should be compared BBB to AAA, because the only element of the array should be AAA.**
*******************received****************
This is NOT the first message received. Size of array: 1
Compare BBB and BBB
解决方案
推荐阅读
- sql - 如何在sql中检查第一列的行是否大于第二列(使用IF语句)
- java - 关于java volatile数组
- excel - 使用相同数据源和缓存的多个数据透视表
- php - PHP比较日期并突出显示相同
- javascript - 没有 toString() 从十进制到十六进制
- sql - Sql在使用东西时重命名结果集中的标题
- kubernetes - Kubernetes/Openshift:如何使用 envFile 从文件系统文件中读取
- jdbc - JDBC Kafka Connect 与 DB2
- dm-script - 通过 dm-script 进行连续摄像头采集,并伴有无模式对话
- c# - 以特定格式从Sql中提取数据到Excel