首页 > 解决方案 > 为什么接收到的元素总是保存在第一位?

问题描述

我有一个程序 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

标签: arrayscstringstrcmp

解决方案


推荐阅读