0

I've a program server.c, where there is an opened socket. It receives some string code (for example "AAA", "BBB", "CCC" ecc.). I have an array in which I save once every different code I receive. For example, if I get "AAA" three times, I save it once in position 0. Then, if I get "BBB", I check that there is not already another instance of "BBB" in the array, and I save it in the same array at the next position, which is 1, and so on. The problem is that the element that arrives is always and in any case saved in position 0, and the comparison is not done correctly. Where am I wrong? code is the string received. Global variables are:

char *received[100];
size_t array_size = 0;

My code is:

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;
    }

}

OUTPUT:

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
WedaPashi
  • 3,561
  • 26
  • 42
TryToLearn
  • 29
  • 1
  • 6
  • 1
    `received[array_size] = code;` ==> `strcpy(received[array_size], code);` and the other associated necessary changes – pmg Sep 07 '21 at 16:20
  • you need to learn the difference between pointer and array. Books are very helpfull – 0___________ Sep 07 '21 at 16:45
  • "you need to learn the difference between pointer and array. Books are very helpfull [sic]" is NOT helpful (I hope you did not write any "Books", and if you do, they will surely NOT be "helpfull") – Andrew Sep 07 '21 at 17:33
  • thanks, unfortunately it is recently that I am programming in C. could you help me understand why it is wrong to use a pointer and how to correct? – TryToLearn Sep 07 '21 at 18:20

0 Answers0